在setOnTouchListener中访问循环变量

时间:2015-05-29 03:46:39

标签: java android ontouchlistener ontouch

我在循环中创建OnTouchListeners:

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。我无法将它们声明为final,因为它们是循环变量。有什么替代方法。

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

我最终只是在循环中获取当前按钮的id:

nil