我在Android类 (非活动) 中动态创建CheckBoxes。所以我需要在我的复选框中添加onClick
动作侦听器,如何实现它。
我正在使用以下代码。
public class DataBaseAdapter extends SQLiteOpenHelper
{
...//onCreate and onUpdate
...
...
public TableLayout getAllAlarmList(Context con)
{
TableLayout tb = new TableLayout(con);
TableRow[] tr = new TableRow[maxCount]; //maxCount is the number of rows
CheckBox[] check = new CheckBox[maxCount]; //maxCount is the number of rows in the database.
for(int i=0;i<maxCount;i++)
{
tr[i]=new TableRow(con);
check[i]= new CheckBox(con); //con is Context class passed as argument.
check[i].setText(Integer.toString(i));
check[i].setId(100+i);
// I have to add onClick Action Listener here.
tr[i].addView(check[i]);
tb.addView(tr[i]);
}
return tb;
}
}
为此我还要跟踪复选框的ID。
答案 0 :(得分:3)
您还可以从非活动类设置任何Listener to Views。试试看:
check[i].setId(100+i);
check[i].setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
switch(buttonView.getId()) {
case R.id.checkbox_meat:
// do your code here...
break;
case R.id.checkbox_cheese:
// do your code here...
break;
// TODO: Veggie sandwich
}
}
});