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

Android:动态地向tableLayout添加自定义复选框,android,layout,checkbox,Android,Layout,Checkbox,如果在代码中动态添加复选框,我应该如何使用自定义复选框?(在java代码上,而不是在XML文件上)我遵循了这一点,但使用它我无法实现我的目标 例如,我有一个tableLayout,我想为每一行添加一个复选框 谢谢大家。你们可以这样做 TableLayout tl=new TableLayout(this); TableRow tr=new TableRow(this); CheckBox chk=new CheckBox(this); chk.setText("Hello");

如果在代码中动态添加复选框,我应该如何使用自定义复选框?(在java代码上,而不是在XML文件上)我遵循了这一点,但使用它我无法实现我的目标

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


谢谢大家。

你们可以这样做

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); 

希望它能帮助您

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

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);

是的,我这样做是为了友好地添加复选框,但是我不能添加自定义复选框,只是默认的复选框。无论如何,谢谢你。