【问题标题】:How to fetch a R id in Java using a variable name如何使用变量名在 Java 中获取 R id
【发布时间】:2015-07-08 04:25:42
【问题描述】:

ImageView test = (ImageView) findViewById(R.id.A1);

给我一​​个 ImageView

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

我试过了

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

正如这个问题所建议的那样:how to call a java method using a variable name?

但是我得到了错误

不能从静态上下文引用非静态方法 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));

【问题讨论】:

  • R 不是这样工作的,getDeclaredMethod 也不是这样工作的。有关 R 的更多帮助,请参阅此问题的已接受答案:stackoverflow.com/questions/6804053/… 由于您必须在 xml 代码中定义 id,为什么需要动态生成的列表?至于getDeclaredMethod,异常是完全正确的。您试图将其称为静态方法。在这里很难说出你想要什么以及为什么想要它。
  • @mttdbrd 知道为什么没有设置整数吗? ps 和 ss 字符串已正确填充且资源存在。

标签: java android


【解决方案1】:

我认为这不是获取 id 的正确方法。

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

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

您可能还需要像这样使用this 引用:

int id = this.getResources().getIdentifier("<String id>","id", getPackageName());

【讨论】:

  • 这几乎是我需要的,除了 'int id' 没有设置。
  • @hellyale 你有什么例外吗,因为它对我有用。
  • 可能是包名不对,可以调用getPackageName()方法获取想要的包名。
  • 感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 2017-08-06
  • 2018-06-04
相关资源
最近更新 更多