1

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.

I am using following 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;
    }

}

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

2
  • what problem u are getting to set check[i].setOnCheckedChangeListener for CheckBox Commented Mar 14, 2013 at 5:33
  • because it is not an Activity class so, unable to write check[i].setOnCheckedChangeListener(new onCheckedChangeListener) as the class do not extend View Class Commented Mar 14, 2013 at 5:37

1 Answer 1

3

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
      }

   }
});
Sign up to request clarification or add additional context in comments.

7 Comments

then how to implement this code in here
@ShardaSingh : ok first remove android:onClick="onCheckboxClicked" from all Checkbox xml .
checkboxes are there dynamically.. so no chance of onCheckboxClicked, in xml
The checkboxes are created dynamically so the previous checkbox has no record for the coming checkbox, and its id.
@ShardaSingh : i have integrated developer.android.com/guide/topics/ui/controls/checkbox.html code in my answer and plz check it if still u have any issue then explain more what u want to do on Checkbox click
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.