Android:动态地将自定义复选框添加到tableLayout

时间:2010-05-23 12:41:27

标签: android layout checkbox

如果我在代码中动态添加复选框,我该怎么做才能使用自定义复选框? (关于不在XML文件上的java代码。)我正在关注this tutorial,但是使用它我无法实现我的目标。

例如,我有一个tableLayout,我想为每个新行添加一个复选框。

谢谢大家。

2 个答案:

答案 0 :(得分:3)

你可以这样做

TableLayout tl=new TableLayout(this);  
 TableRow tr=new TableRow(this);  
 CheckBox chk=new CheckBox(this);  
 chk.setText("Hello");  
 tr.addView(chk);         
 tl.addView(tr);  
 setContentView(tl); 

希望有所帮助

答案 1 :(得分:3)

如果您想添加自定义复选框,请尝试以下操作:

StateListDrawable stateList = new StateListDrawable();
int statePressed = android.R.attr.state_pressed;
int stateChecked = android.R.attr.state_checked;
stateList.addState(new int[] {-stateChecked}, new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.check_3)));
stateList.addState(new int[] {stateChecked}, new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.check_1)));
stateList.addState(new int[] {statePressed}, new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.check_2)));
final CheckBox box = new CheckBox(this);
box.setButtonDrawable(stateList);