Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 451
Ultimo_m Avatar asked Apr 22 '26 15:04

Ultimo_m


1 Answers

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);
like image 92
petey Avatar answered Apr 24 '26 05:04

petey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!