使用循环将按钮设置为onclicklistener [英] Using a loop to set the buttons onclicklistener
本文介绍了使用循环将按钮设置为onclicklistener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用循环来设置单击时每个按钮的动作(因为大多数按钮将仅返回其文本值),但是我收到一条错误消息,指出从内部内部访问变量'i'类,则需要声明为最终的".我该如何解决?
I am trying to use a loop to set the action for each button when clicked (since most of the buttons will just return their text value), however I am getting an error stating "variable 'i' is accessed from within inner class, needs to be declared final". How can I get around this?
这就是我得到的
String getValuesPressed(){
for(int i = 0; i < buttonList.length; i++){
buttonList[i].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(i == 0){//error occurs here
//do stuff
}
}
});
}
return textOnScreen;
}
推荐答案
您可以将i
的值复制到临时最终变量中,例如-
You can copy the value of i
in to a temp final variable as -
for (int i = 0; i < buttonList.length; i++) {
final int finalI = i;
buttonList[i].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (finalI == 0) {//error occurs here
//do stuff
}
}
});
}
这篇关于使用循环将按钮设置为onclicklistener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文