Cant setId to view programmatically with AndroidStudio

I want to add a view programmatically to the parent view, my view is RadioButton

. I also want to set the Id for the view I am adding to RadioGroup

. But when I do this it results in an error: 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 don't know why it is giving me this error.

I found that one solution would be to create a class MyRadioButton

that extends

RadioButton

there I could add a variable int MYID;

, and then add getters

and setters

for this representation.

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

Thank!

EDIT: Another workaround is to use setTag()

(I used it for horizontal view with ImageView

added dynamically and it helps me determine which one was clicked)

+3


source to share


1 answer


If you only support API 17 and above,

you can call View.generateViewId

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

      

Otherwise for apis below 17,

  • open the project folder res/values/

  • create xml file named 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);

      

+4


source







All Articles