java - Android:通过id查找按钮

标签 java android

我在查找按钮时遇到了问题。我有一个 AlertDialog我从 5 个选项中选择一个。当我选择一个选项时,我想更改我单击的按钮的颜色。我在 <RealativeLayout> 中的 xml 文件中声明了按钮但是当我试图通过 id 找到我的按钮时(id 就像“id1”,“id2”......)使用 findViewById方法,有个错误,说不能像我这样使用这个方法:

AlertDialog.Builder builder = new AlertDialog.Builder(StartGameActivity.this);

builder.setTitle(R.string.pickColor);
builder.setItems(R.array.colorArray, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        Button btn_tmp;
        String theButtonId = "id";
        theButtonId = theButtonId+(String.valueOf(which));
        btn_tmp = (Button) findViewById(theButtonId);
    }
});

我该如何解决这个问题,或者我应该使用其他方法?

编辑:

我想我的问题已经解决了。我使用了 Button 的方法之一:getId(),如下所示:

final int id = clickedButton.getId();
final ImageButton btn_tmp;
btn_tmp = (ImageButton)findViewById(id);

最佳答案

背景:ID 本质上是变量

XML 文件中,我们为资源提供 ID,然后编译器使用所有这些来生成 gen/R.java。所以本质上,这些 ID 是属于 R 类的 int 变量。 R.java 的一个例子:

// btw this file should never be edited!
public final class R {
  public static final class id {
    public static final int id1=0x7f0100aa;
    public static final int id2=0x7f0100ab;
  }
}

仅仅因为存在包含有效变量名称的 String (R.id.id1),它无法神奇地访问该变量。为此,可以使用 reflection .然而,在这种情况下,我认为这是一个不必要的并发症,甚至会是 slower .

findViewById 需要一个 ID(整型变量):

您不能向该函数提供 String。您应该使用整数值,特别是那些与 R.java 中的 int 变量相对应的值。 例如:

findViewById(R.id.id1) // for your 1st button

解决方案:

您可以动态选择整数值:

AlertDialog.Builder builder = new AlertDialog.Builder(StartGameActivity.this);

builder.setTitle(R.string.pickColor);
builder.setItems(R.array.colorArray, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        Button btn_tmp;
        int chosenID=-1;

        switch (which) {
        case 1:   chosenID=R.id.id1;
                  break;
        case 2:   chosenID=R.id.id2;
                  break;
        }
        btn_tmp = (Button) findViewById(chosenID);
    }
});

还建议使用更多解释性 ID,例如:buttonDoThisbuttonDoThat

关于java - Android:通过id查找按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14286886/

相关文章:

java - Android @Override 用法

java - 无法启动 Activity ComponentInfo (LOGCAT)

java - 使用 Spring cloud SqsListener 尝试读取消息失败的阈值

java - 无法停止 retrofit 发送

android - 如果我使用 Moshi,为什么任务 ':app:kaptDebugKotlin' 执行失败?

android - StartTimer() 应该在按钮单击事件完成后调用,但它在 onclick 事件之前执行

android - 当按下后退按钮时,android显示空白页

java - JSP页面仅在IE浏览器中出现错误

java - 需要从 Struts2 迭代器内部访问我的操作类中的 HashMap

java - 调用 Spring bean 的函数接口(interface)