java - 无法使用 Android Studio 以编程方式为 View 设置 Id

标签 java android view android-studio

我想以编程方式将 View 添加到我的父 View ,我的 View 是一个 RadioButton。我还想为我在 RadioGroup 中添加的 View 设置一个 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 ; 然后为该 View 添加 getterssetters

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

谢谢!

编辑: 另一种解决方法是使用 setTag() (我将它用于动态添加 ImageView 的水平 View ,它帮助我检测点击了哪个)

最佳答案

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

您可以调用View.generateViewId

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

否则对于低于17的api,

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

关于java - 无法使用 Android Studio 以编程方式为 View 设置 Id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27624798/

相关文章:

java - HashMap 中的每隔一个字母

android - 如何删除android中的sim卡联系人

java - 如何在 Eclipse Android 开发中使用自定义 View ?

android - 在没有自定义 View 的情况下将 editText 放在 AlertDialog 中?

java - JAXB xsd 如何像引用一样使用数组成员

java - Android:将 TextView 作为参数传递给外部函数返回 nullpointerException

java - 如何将 map 转换为对象数组列表?

java - 当 EditText 输入为空时 Android 应用程序崩溃

java - 无法在 Activity 内调用 View 对象的方法

java - Jersey 在 PUT 上返回 405