gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:21:00 27 4
gpt4 key购买 nike

我想以编程方式将 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com