Sharda Singh
Sharda Singh

Reputation: 747

Dynamically Add onClick ActionListener to CheckBox in Android

I am creating an application, which creates checkboxes dynamically from the number of entries in the database.

The code runs fine. and creates number of checkboxes. But I want to add onClick Action Listener to the CheckBoxes, dynamically. How to do this.

I am posting the code here:

SQLiteDatabase db = this.getReadableDatabase();

String countQuery = "SELECT  * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);

int maxCount = cursor.getCount();
CheckBox[] check = new CheckBox[maxCount];

cursor.moveToFirst();
int checkboxid = 100;
int alarm_id;
for(int i=0;i<maxCount;i++)
{
    check[i]= new CheckBox(this);
setCheckBoxId(i+maxCount);
}

Now how to add actionlistener to these dynamically created CheckBoxes.

Upvotes: 0

Views: 2669

Answers (2)

Dodge
Dodge

Reputation: 8307

below check[i]= new CheckBox(this); add this, and your CheckBoxes will have a all clicklistener

check[i].setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        // your code to be executed on click :)
                    }
                });

Upvotes: 2

Aiden Fry
Aiden Fry

Reputation: 1682

check[i]= new CheckBox(this);
check[i].setOnClickListener(this);

You will want to check against the checkbox id or set a tag for the text boz when creating it.

check[i].setTag(someIdentifier);

then use the method

@Override
public void onClick(View v) {
                 if (v.getTag.equals(someIdentifier)){
                    //do stuff here
                  }

        }

Upvotes: 2

Related Questions