Java – You cannot use Android Studio to programmatically set IDs for Views

You cannot use Android Studio to programmatically set IDs for Views… here is a solution to the problem.

You cannot use Android Studio to programmatically set IDs for Views

I want to programmatically add a View to my parent View, which is a RadioButton. I also want to set an ID for the View I added in RadioGroup. But when I do this, it gives me 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 this error was given to me.

One solution I found was to create the MyRadioButton class, which extends RadioButton and then I could add a variable int MYID; Then add getters and setters for the View.

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

Thanks!

Edit:
Another workaround is to use setTag().
(I use it for dynamically adding a horizontal View of the ImageView, which helps me detect which one was clicked)

Solution

If you only support API 17 and later

You can call View.generateViewId

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

Otherwise for APIs below 17,

  1. Open the res/values/ folder for the project
  2. Create an XML file named IDS.xml

Contains the following:

<?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);

Related Problems and Solutions