无法使用Android Studio以编程方式为视图设置ID

时间:2014-12-23 17:01:18

标签: java android view android-studio

我想以编程方式将视图添加到我的父视图中,我的视图是RadioButton。我还想为RadioGroup中添加的视图设置ID。但当我这样做时,它给我一个错误: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.

我不知道为什么它会给我这个错误。

我发现一个解决方案是创建MyRadioButton extends RadioButton类,我可以在其中添加变量int MYID;,然后添加getters和这个观点setters

但这是一种解决方法,有没有人知道这个问题的解决方案?

谢谢!

修改 另一种解决方法是使用setTag() (我已将它用于动态添加ImageView的水平视图,它可以帮助我检测哪一个被点击了)

1 个答案:

答案 0 :(得分:4)

如果您只支持API 17及更高版本,

您可以致电View.generateViewId

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

否则apis低于17,

  1. 打开项目的res/values/文件夹
  2. 创建名为ids.xml
  3. 的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);