我想以编程方式将 View 添加到我的父 View ,我的 View 是一个 RadioButton
。我还想为我在 RadioGroup
中添加的 View 设置一个 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 ;
然后为该 View 添加 getters
和 setters
。
但这是一种解决方法,有谁知道这个问题的解决方案吗?
谢谢!
编辑:另一种解决方法是使用 setTag()
(我将它用于动态添加 ImageView
的水平 View ,它帮助我检测点击了哪个)
如果您只支持 API 17 及更高版本,
您可以调用View.generateViewId
ImageButton mImageButton = new ImageButton(this);
mImageButton.setId(View.generateViewId());
否则对于低于17的api,
- 打开项目的
res/values/
文件夹
- 创建一个名为
ids.xml
的 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);
我是一名优秀的程序员,十分优秀!