gpt4 book ai didi

java - 访问 setOnTouchListener 中的循环变量

转载 作者:行者123 更新时间:2023-12-02 04:38:07 25 4
gpt4 key购买 nike

我正在循环中创建 OnTouchListener:

for(int i = 0; i < buttons.length; i++){
for(int j = 0; j < buttons[i].length; j++ ){
String buttonID = "button" + i + j;
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i][j] = (Button) findViewById(resID);
buttons[i][j].setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
if (arg1.getAction() == MotionEvent.ACTION_DOWN){
socket.emit("button down", "button" + i + j);
return false;
}
if (arg1.getAction() == MotionEvent.ACTION_UP){
socket.emit("button up", "button" + i + j);
return false;
}
return true;
}
});
}
}

如何在 setOnTouchListener 函数中访问变量 i 和 j。我不能将它们声明为最终的,因为它们是循环变量。还有什么替代方法吗?

最佳答案

for(int i = 0; i < buttons.length; i++){
final int iNow = i;
for(int j = 0; j < buttons[i].length; j++ ){
final int jNow = j;
String buttonID = "button" + i + j;
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i][j] = (Button) findViewById(resID);
buttons[i][j].setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
if (arg1.getAction() == MotionEvent.ACTION_DOWN){
socket.emit("button down", "button" + iNow + jNow);
return false;
}
if (arg1.getAction() == MotionEvent.ACTION_UP){
socket.emit("button up", "button" + iNow + jNow);
return false;
}
return true;
}
});
}
}

关于java - 访问 setOnTouchListener 中的循环变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30520774/

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