安卓:使用findViewById()用字符串/在一个循环 [英] Android: Using findViewById() with a string / in a loop
本文介绍了安卓:使用findViewById()用字符串/在一个循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在做一个Android应用程序,那里有几百个按钮,每一个具体的回调组成的视图。现在,我想设置,而不必写了数百code(对于按钮各一个)的线条和回调使用循环。
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);
}
}
在此先感谢!
Thanks in advance!
推荐答案
您应该使用则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", "com.sample.project");
buttons[i][j] = ((Button) findViewById(resID));
buttons[i][j].setOnClickListener(this);
}
}
这篇关于安卓:使用findViewById()用字符串/在一个循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文