Aashutosh Sharma
Aashutosh Sharma

Reputation: 1483

How to set the Id of new added radioButton in java file in android?

I am adding RadioButtons in my view by using a for loop, now I want to set a unique ID for each RadioButton.

for (int item = 0; item < 5; item++) {
    child = new RadioButton(this);
    itemRadioGroup.addView(child);
    child.setId(item);
}

Toast.makeText(getApplicationContext(), 
        String.valueOf(child.getID()), Toast.LENGTH_SHORT).show();

I want to set the ID of first button as 1, second button as 2, third as 3 and so on. But when I try to display the ID with a Toast message it shows me some garbage value rather than my set ID. How can I set ID properly?

Upvotes: 0

Views: 5269

Answers (1)

5hssba
5hssba

Reputation: 8079

I think it is because 0 is not a integer and your a giving an id of button as 0. where as the ids can only be positive integers..

  RadioButton child[]=new RadioButton[5];
  for (int item = 1; item <= 5; item++) {
 child[i]= new RadioButton(this);
 itemRadioGroup.addView(child[i]);
 child[i].setId(item);
 Toast.makeText(getApplicationContext(),child.getID()+ " ", Toast.LENGTH_SHORT).show();
 }
//gets the checked radiobuttons ids

for (int item = 1; item <= 5; item++) {
if(child[i].isChecked()){

 Toast.makeText(getApplicationContext(),child[i].getID()+ " ", Toast.LENGTH_SHORT).show();

 }
}

Upvotes: 1

Related Questions