添加的onClick动作侦听器动态创建的CheckBox [英] Add onClick Action Listener for dynamically created CheckBox

查看:164
本文介绍了添加的onClick动作侦听器动态创建的CheckBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Android类创建的CheckBox动态 (不活动)。所以,我需要的onClick 动作侦听器添加到我的复选框,如何实现这一点。

I am creating CheckBoxes Dynamically in an Android Class (Not Activity). So I need to add onClick Action Listener to my checkboxes, how to implement this.

我使用以下code。

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的轨道。

For this I am also keeping a track of the ids of the checkboxes.

推荐答案

您也可以设置任意监听从非活性类视图。尝试为:

you can also set any Listener to Views from non-activity class. try it as :

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
      }

   }
});

这篇关于添加的onClick动作侦听器动态创建的CheckBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆