2013-03-14 79 views
1

我在Android类中动态创建CheckBox动作(Not Activity)。所以我需要将onClick Action Listener添加到我的复选框,如何实现这一点。为动态创建的CheckBox添加点击动作侦听器

我正在使用以下代码。

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

什么问题ü越来越设置'检查[I] .setOnCheckedChangeListener'的复选框 – 2013-03-14 05:33:44

+0

,因为它不是一个Activity类,因此,无法写入 '检查[I] .setOnCheckedChangeListener(新onCheckedChangeListener)' 由于类不扩展查看类 – 2013-03-14 05:37:30

回答

3

您还可以将任何侦听器设置为来自非活动类的视图。尝试,因为:

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 
     } 

    } 
}); 
+0

那么如何实现[这里的代码](http://developer.android.com/guide/topics/ui/controls/checkbox.html) – 2013-03-14 05:43:27

+0

@ShardaSingh:确定首先从所有复选框xml中删除'android:onClick =“onCheckboxClicked”'。 – 2013-03-14 05:44:44

+0

没有让你。 – 2013-03-14 05:46:12

相关问题