Android:在循环中使用带字符串/的findViewById()

use*_*536 59 android button clicklistener

我正在制作一个Android应用程序,其中有一个由数百个按钮组成的视图,每个按钮都有一个特定的回调.现在,我想使用循环设置这些回调,而不是必须编写数百行代码(对于每个按钮).

我的问题是:如何在不静态地输入每个按钮ID的情况下使用findViewById?这是我想做的事情:

    for(int i=0; i<some_value; i++) {
       for(int j=0; j<some_other_value; j++) {
        String buttonID = "btn" + i + "-" + j;
        buttons[i][j] = ((Button) findViewById(R.id.buttonID));
        buttons[i][j].setOnClickListener(this);
       }
    }
Run Code Online (Sandbox Code Playgroud)

提前致谢!

War*_*ith 106

你应该使用 getIdentifier()

for(int i=0; i<some_value; i++) {
   for(int j=0; j<some_other_value; j++) {
    String buttonID = "btn" + i + "-" + j;
    int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
    buttons[i][j] = ((Button) findViewById(resID));
    buttons[i][j].setOnClickListener(this);
   }
}
Run Code Online (Sandbox Code Playgroud)

  • "com.sample.project"可以替换为getPackageName(). (23认同)
  • 请注意,根据我的经验,这样做会让您的表现非常差. (2认同)

Ric*_*use 6

您可以尝试创建一个包含所有按钮 ID 的 int[],然后对其进行迭代:

int[] buttonIDs = new int[] {R.id.button1ID, R.id.button2ID, R.id.button3ID, ... }

for(int i=0; i<buttonIDs.length; i++) {
    Button b = (Button) findViewById(buttonIDs[i]);
    b.setOnClickListener(this);
}
Run Code Online (Sandbox Code Playgroud)