Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/386.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
如何使用变量名在Java中获取R id_Java_Android - Fatal编程技术网

如何使用变量名在Java中获取R id

如何使用变量名在Java中获取R id,java,android,Java,Android,ImageView测试=(ImageView)findviewbyd(R.id.A1) 给我一个图像视图 我希望使用字符串变量来获取一系列ID,而不是A1 我试过了 Method Pmethod=Class.getDeclaredMethod(“(ImageView)findViewById(Id.R.”+dest.toString()); 正如在这个问题中所提到的: 但是我得到了错误 无法从静态上下文引用非静态方法getDeclaredMethod 有办法解决这个问题吗 我的最新尝试:

ImageView测试=(ImageView)findviewbyd(R.id.A1)

给我一个图像视图

我希望使用字符串变量来获取一系列ID,而不是A1

我试过了

Method Pmethod=Class.getDeclaredMethod(“(ImageView)findViewById(Id.R.”+dest.toString());

正如在这个问题中所提到的:

但是我得到了错误

无法从静态上下文引用非静态方法getDeclaredMethod

有办法解决这个问题吗

我的最新尝试:

        String ps = "P"+ dest.toString();
        String ss = "S"+ dest.toString();
        int piecelayertier = getResources().getIdentifier(ps,"id","com.donthaveawebsite.mhy.ocfix");
        int selectorlayertier = getResources().getIdentifier(ss,"id","com.donthaveawebsite.mhy.ocfix");
        ImageView test =(ImageView)findViewById(piecelayertier);

        spot.TieAppearance((ImageView)findViewById(piecelayertier));
        spot.TieSelector((ImageView)findViewById(selectorlayertier));

我认为这不是一个正确的获取身份证的方法

您可以尝试使用字符串变量获取以下id:

int id = getResources().getIdentifier("<String id>","id","<package name>");
ImageView test =(ImageView)findViewById(id);

R不是这样工作的,getDeclaredMethod也不是这样工作的。有关R的更多帮助,请参阅此问题的公认答案:既然您必须在xml代码中定义ID,为什么需要动态生成的列表?至于getDeclaredMethod,异常是完全正确的。您试图将其称为静态方法。很难说您想要什么以及为什么想要它。@mttdbrd知道为什么不设置int吗?ps和ss字符串已正确填充,并且资源已存在。这几乎就是我所需要的,只是“int id”未设置。@hellyale您是否有任何异常,因为它对我有效。可能是因为Packagege名称错误,您可以调用
getPackageName()
方法获取所需的软件包名称。感谢您的帮助!
int id = this.getResources().getIdentifier("<String id>","id", getPackageName());