我以编程方式制作了3X2单选按钮。
这是我的tableLayout
public class ToggleButtonGroupTableLayout extends TableLayout implements
OnClickListener {
private static final String TAG = "ToggleButtonGroupTableLayout";
private RadioButton activeRadioButton;
/**
* @param context
*/
public ToggleButtonGroupTableLayout(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
/**
* @param context
* @param attrs
*/
public ToggleButtonGroupTableLayout(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
@Override
public void onClick(View v) {
final RadioButton rb = (RadioButton) v;
if (activeRadioButton != null) {
activeRadioButton.setChecked(false);
}
rb.setChecked(true);
activeRadioButton = rb;
}
/*
* (non-Javadoc)
*
* @see android.widget.TableLayout#addView(android.view.View, int,
* android.view.ViewGroup.LayoutParams)
*/
@Override
public void addView(View child, int index,
android.view.ViewGroup.LayoutParams params) {
super.addView(child, index, params);
setChildrenOnClickListener((TableRow) child);
}
/*
* (non-Javadoc)
*
* @see android.widget.TableLayout#addView(android.view.View,
* android.view.ViewGroup.LayoutParams)
*/
@Override
public void addView(View child, android.view.ViewGroup.LayoutParams params) {
super.addView(child, params);
setChildrenOnClickListener((TableRow) child);
}
private void setChildrenOnClickListener(TableRow tr) {
final int c = tr.getChildCount();
for (int i = 0; i < c; i++) {
final View v = tr.getChildAt(i);
if (v instanceof RadioButton) {
v.setOnClickListener(this);
}
}
}
public int getCheckedRadioButtonId() {
if (activeRadioButton != null) {
return activeRadioButton.getId();
}
return -1;
}
}
这是我的主要活动
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l = (LinearLayout) findViewById(R.id.mainl);
ToggleButtonGroupTableLayout t=new ToggleButtonGroupTableLayout(this);
TableRow r1=new TableRow(this);
TableRow r2=new TableRow(this);
TableRow r3=new TableRow(this);
b1=new RadioButton(this);
b2=new RadioButton(this);
b3=new RadioButton(this);
b4=new RadioButton(this);
b5=new RadioButton(this);
b6=new RadioButton(this);
b7=new RadioButton(this);
b1.setText("b1");
b2.setText("b2");
b3.setText("b3");
b4.setText("b4");
b5.setText("b5");
b6.setText("b6");
b7.setText("b7");
r1.addView(b1);
r1.addView(b2);
r1.addView(b3);
r2.addView(b4);
r2.addView(b5);
r2.addView(b6);
r3.addView(b7);
t.addView(r1);
t.addView(r2);
t.addView(r3);
l.addView(t);
t.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
RadioButton rb = (RadioButton) v;
Log.e("msg ", rb.getText().toString());
Log.e("msg ", "clciked");
}
});
}
我需要做以下两件事
答案 0 :(得分:1)
要查找单选按钮的文本,请使用radiobutton.getText()方法 默认情况下,为xml中的一个单选按钮选择make setChecked为该单选按钮