我想以编程方式将视图添加到我的父视图中,我的视图是RadioButton
。我还想为RadioGroup
中添加的视图设置ID。但当我这样做时,它给我一个错误:mRadioButton.setId(321);
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.
我不知道为什么它会给我这个错误。
我发现一个解决方案是创建MyRadioButton
extends
RadioButton
类,我可以在其中添加变量int MYID;
,然后添加getters
和这个观点setters
。
但这是一种解决方法,有没有人知道这个问题的解决方案?
谢谢!
修改
另一种解决方法是使用setTag()
(我已将它用于动态添加ImageView
的水平视图,它可以帮助我检测哪一个被点击了)
答案 0 :(得分:4)
如果您只支持API 17及更高版本,
您可以致电View.generateViewId
ImageButton mImageButton = new ImageButton(this);
mImageButton.setId(View.generateViewId());
否则apis低于17,
res/values/
文件夹ids.xml
具有以下内容:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="imageButtonId1" type="id" />
</resources>
然后在你的代码中,
ImageButton mImageButton = new ImageButton(this);
mImageButton.setId(R.id.imageButtonId1);