【问题标题】:What is the value of R.id.ImageButton?R.id.ImageButton 的值是多少?
【发布时间】:2014-05-02 18:59:18
【问题描述】:

我有 16 个图像按钮,所以我创建了一个图像按钮数组。我想用一个 for 循环来初始化它们,我不想一个一个地这样做,虽然我不知道这是否可能。 对于一个图像按钮,它会是这样的:

imgbtn[0] = (ImageButton)findViewById(R.id.imgButton1);

我看到 R.id.smth 部分是一个整数。它是否在某处说,imgButtons 的整数值从哪里开始?这样我就可以这样:

int value = R.id.imgButton1;
for(int i = 0; i < imgbtn.length; i++)
{
     imgbtn[i] = (ImageButton)findViewById(value);
     value++;   //or something along these lines
}

【问题讨论】:

    标签: java android loops imagebutton


    【解决方案1】:

    ID 不是增量分配的,实际上是非常随机的,因此无法猜测资源 ID 是什么。您需要的是通过 getIdentifier() 方法实际动态获取 id

    int value = 1;
    for(int i = 0; i < imgbtn.length; i++){
        int resId = getResources().getIdentifier("imgButton" + value, "id", this.getPackageName());
        imgbtn[0] = (ImageButton) findViewById(resId);
        value++;
    }
    

    getResources().getIdentifier(tag, type, package) 将返回存储在您的图像资源 (R) 中的实际 int 值。您可以使用它来动态查找视图。

    【讨论】:

    • 谢谢,这会派上用场的。
    【解决方案2】:

    不,上面的代码不起作用,因为分配的整数不一定要加一。此外,整数是在构建程序时随机生成的。

    如果您查看您的 gen/R.id 文件,您会看到如下内容:

    public static final class id {
        public static final int action_settings=0x7f080001;
        public static final int dimensionPlusView=0x7f080000;
    }
    public static final class layout {
        public static final int activity_main=0x7f030000;
    }
    public static final class menu {
        public static final int main=0x7f070000;
    }
    public static final class string {
        public static final int action_settings=0x7f050001;
        public static final int app_name=0x7f050000;
        public static final int photo_credit=0x7f050002;
    }
    

    【讨论】:

    • 打我一拳。 +1。基于 Blaine 所说,整数是随机分配的。如果您添加更多小部件/资源,它们也会不断变化。这些是在使用 Android 项目创建的 R.java 文件中自动创建的。
    • 不要直接弄乱 id - 改用 getResources().getIdentifier() 方法
    • 我并不是建议你搞乱这些,而是​​表明它们不是“整数”(1、2、3、4 等)。
    • 不用担心 - 你有我今天倒数第二个 +1。 ;)
    • @BobMalooga 如果我能给你一个 +1 的使用 penultimate 我会...大声笑...
    猜你喜欢
    • 2011-01-24
    • 2013-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 2012-03-06
    • 2017-11-13
    • 1970-01-01
    相关资源
    最近更新 更多