Skip to content Skip to sidebar Skip to footer

Getting Checkboxid For Dynamically Created Checkbox?

I have dynamically created checkbox.I want Id of selected checkbox.but I am getting Id of only last checkbox. for eg. if 5 checkboxes created then it is showing Id of 5th checkb

Solution 1:

the problem is, that you adding a clicklistener just to the last added checkbox! So add a listener to the checkbox in your while loop.

Solution 2:

put inside loop and access using buttonView like this:

checkBox.setOnCheckedChangeListener(newCompoundButton.OnCheckedChangeListener() 
{
  @OverridepublicvoidonCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    System.out.println(isChecked);
                    System.out.println(buttonView.getText());
});

Solution 3:

This problem can be solved when we apply "setOnClickListener" on child check box of parent dynamic created Linear layout. I have added check box using "getLayoutInflater()" and set id for each check box.For it u can see below code.

for (int i = 0; i < JAS.length(); i++) {

   View child = getLayoutInflater().inflate(R.layout.return_child, null);
   chk = (CheckBox) child.findViewById(R.id.Product);
   chk.setText(c.optString("name"));
   chk.setId(i);

   ll.addView(child);

   chk.setOnClickListener(new View.OnClickListener() {
       publicvoidonClick(View v) {
           String chk = null;
           chk = Integer.toString(v.getId());
           if (((CheckBox) v).isChecked()) {
               selchkboxlist.add(chk);

           } else {
               selchkboxlist.remove(chk);
           }
       }
   });
}

Here selchkboxlist is "List" same as below :

List selchkboxlist = new ArrayList();

Now On button click you can apply below code for accessing id of selected check box.

ReturnProducts.setOnClickListener(newView.OnClickListener() {
    @OverridepublicvoidonClick(View v) {

        for (int p=0;p<selchkboxlist.size();p++){
            StringLength= selchkboxlist.get(p);
            intln= Integer.parseInt(Length);
            Toast.makeText(ReturnOrders.this, ""+ln, Toast.LENGTH_LONG).show();
        }

    }
});

Post a Comment for "Getting Checkboxid For Dynamically Created Checkbox?"