Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/223.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何使用字符串变量按id查找视图?_Android_Findviewbyid - Fatal编程技术网

Android 如何使用字符串变量按id查找视图?

Android 如何使用字符串变量按id查找视图?,android,findviewbyid,Android,Findviewbyid,我正在编写一个android应用程序,并试图用嵌套循环初始化一个按钮网格 我最初是通过研究找到了这个当前的解决方案,但我无法找出哪里出了问题 for (int i = 0; i < piles.length; i++) for (int j = 0; j < piles[0].length; j++) { id = getResources().getIdentifier("R.id." + "b" + numplayaz + Integer.toString(

我正在编写一个android应用程序,并试图用嵌套循环初始化一个按钮网格

我最初是通过研究找到了这个当前的解决方案,但我无法找出哪里出了问题

for (int i = 0; i < piles.length; i++)
  for (int j = 0; j < piles[0].length; j++) {

        id = getResources().getIdentifier("R.id." + "b" + numplayaz + Integer.toString(i) + Integer.toString(j), "id","app.dj");
        bpiles[i][j] = ((Button) this.findViewById(id));
        bpiles[i][j].setOnClickListener(this);
   }
 }
for(int i=0;i
由于某些原因,当id始终设置为0,因此bpiles[0][0]设置为null,然后获取null指针异常

我试过分配一些小的解决方案,但都不起作用

有没有人知道我的问题是什么,或者有更好的解决办法

哦,当我看到这篇文章时,我想到了这个。
0表示找不到id

  • 您是否已检查您引用的所有ID是否存在

  • 使用getPackageName()而不是“app.dj”。也许是不完整的


  • 构建可绘制名称后,可以使用此函数获取其Id:

    public static int getDrawableByName( String name ) {
        int drawableId = 0;
    
        try {
             Class res = R.drawable.class;
             Field field = res.getField( name );
             drawableId = field.getInt(null);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    
        return drawableId;
    }
    

    看起来
    getIdentifier()
    的第一个参数是错误的:

    id = getResources().getIdentifier("R.id." + "b" + numplayaz + Integer.toString(i) + Integer.toString(j), "id","app.dj");
    //             Do not use "R.id." ^^^^^^^
    
    我们已经知道您正在尝试引用
    R
    ,第二个参数指定类型
    “id”
    。也要改变它:

    id = getResources().getIdentifier("b" + numplayaz + Integer.toString(i) + Integer.toString(j), "id", "app.dj");
    


    此外,字符串的
    +
    运算符应该优先,这样您就可以
    “b”+numpayaz+i+j
    。但是StringBuilder可能是你最快的方法,也更容易阅读。

    你的包名真的是
    app.dj
    ,你试过使用
    getPackageName()
    吗?还张贴了如何设置每个按钮的id。在哪里提到了可绘制的内容?