gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:23:22 25 4
gpt4 key购买 nike

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

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

    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(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4865244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com