Android:在循环中使用带有字符串/的 findViewById() [英] Android: Using findViewById() with a string / in a loop

查看:27
本文介绍了Android:在循环中使用带有字符串/的 findViewById()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm making an android application, where there is a view composed of hundreds of buttons, each with a specific callback. Now, I'd like to set these callbacks using a loop, instead of having to write hundreds of lines of code (for each one of the buttons).

我的问题是:如何使用 findViewById 而不必静态输入每个按钮 ID?这是我想要做的:

My question is: How can I use findViewById without statically having to type in each button id? Here is what I would like to do:

    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);
       }
    }

提前致谢!

推荐答案

你应该使用 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);
   }
}

这篇关于Android:在循环中使用带有字符串/的 findViewById()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆