【问题标题】:Cant setId for a view programatically with AndroidStudio无法使用 Android Studio 以编程方式为视图设置 ID
【发布时间】:2014-12-23 17:01:18
【问题描述】:

我想以编程方式将视图添加到我的父视图中,我的视图是 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;,然后为此视图添加getterssetters

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

谢谢!

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

【问题讨论】:

    标签: java android view android-studio


    【解决方案1】:

    如果您只支持 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);
    

    【讨论】:

    • 我会将您的答案标记为正确,但您现在应该知道我给出的解决方案适用于所有情况,但不幸的是一种解决方法,对于我的问题,我意识到我不需要设置Id :) 暂时:D
    猜你喜欢
    • 1970-01-01
    • 2015-07-05
    • 2016-11-10
    • 2014-04-26
    • 2015-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多