Ultimo_m
Ultimo_m

Reputation: 4897

Cant setId for a view programatically with AndroidStudio

I want to add view programatically to my parent view, my view is a RadioButton. I also want to set an Id for the view that I add in RadioGroup. But when I do this it gives me an error in: mRadioButton.setId(321);

enter image description here

Reports two types of problems:
Supplying the wrong type of resource identifier. For example, when calling Resources.getString(int id), you should be passing R.string.something, not R.drawable.something.
Passing the wrong constant to a method which expects one of a specific set of constants. For example, when calling View#setLayoutDirection, the parameter must be android.view.View.LAYOUT_DIRECTION_LTR or android.view.View.LAYOUT_DIRECTION_RTL.

I dont know why it gives me this error.

I found that one solution would be to create MyRadioButton class which extends RadioButton and there I could add a variable int MYID; and then add getters and setters for this view.

But this is a workaround, does anyone know the solution of this problem ?

Thanks!

EDIT: Another workaround is to use setTag() (I have used it for a horizontal view with ImageView's added dynamically and it helps me to detect which one was clicked)

Upvotes: 3

Views: 2082

Answers (1)

petey
petey

Reputation: 17140

If you are only supporting API 17 and higher,

you can call View.generateViewId

ImageButton mImageButton = new ImageButton(this);
mImageButton.setId(View.generateViewId());

Otherwise for apis lower than 17,

  1. open your project's res/values/ folder
  2. create an xml file called ids.xml

with the following content:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="imageButtonId1" type="id" />
</resources>

then in your code,

ImageButton mImageButton = new ImageButton(this);
mImageButton.setId(R.id.imageButtonId1);

Upvotes: 4

Related Questions