为九个按钮编写for循环

时间:2016-03-06 22:11:07

标签: java android loops

我正在Android Studio中为大学项目创建一个简单的淘气和跨越游戏,但我很难为循环通过阵列的九个按钮中的每一个创建一个for循环。我怎么做这个呢?

以下是在OnClickListener中设置事件侦听器的九个按钮的代码。

Button[] buttons = new Button[10];
        buttons[1] = (Button) findViewById(R.id.one);
        buttons[2] = (Button) findViewById(R.id.two);
        buttons[3] = (Button) findViewById(R.id.three);
        buttons[4] = (Button) findViewById(R.id.four);
        buttons[5] = (Button) findViewById(R.id.five);
        buttons[6] = (Button) findViewById(R.id.six);
        buttons[7] = (Button) findViewById(R.id.seven);
        buttons[8] = (Button) findViewById(R.id.eight);
        buttons[9] = (Button) findViewById(R.id.nine);

1 个答案:

答案 0 :(得分:2)

您可以为所有按钮设置单击侦听器,然后在视图ID上使用switch语句来确定单击了哪个按钮。你应该将数组从0开始,而不是1。

private final View.OnClickListener mListener = new View.OnClickListener() {
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.one:
                // do stuff;
                break;
            case R.id.two:
                // do stuff;
                break;
            case R.id.three:
                // do stuff;
                break;
            case R.id.four:
                // do stuff;
                break;
            // add more
        }
    }
}

然后只需将此侦听器设置为按钮

即可
for (int i = 0; i < 9; ++i) {
    buttons[i].setOnClickListener(mListener);
}
相关问题