首页 > 解决方案 > Android - 我将如何动态更改 clickListener

问题描述

所以我有一组按钮,其中一个是正确答案,而其他 3 个是不正确的。然而,在每个问题上,正确的按钮都会改变。我将如何更新我的点击监听器?这似乎是一个足够简单的问题,也许我在这里看不到明确的答案......

到目前为止,这是我的代码,在此先感谢:

int correctIndex=newQuestion(questionTextView,answerButtons);//CREATES A NEW QUESTION and returns the correct index (0-3);

answerButtons[correctIndex].setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        correctDialog(questionTextView,answerButtons);
    }
});

for (int i = 0; i < 4; i++) {
    final int j = i;
    if (j != correctIndex) {
        answerButtons[j].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                wrongDialog(questionTextView, answerButtons);
            }
        });
    }
}

标签: javaandroidandroid-studio

解决方案


创建一个通用侦听器,您可以将其添加到所有按钮中,并在该侦听器中处理用于根据需要确定哪个是正确的逻辑。例如:

class YourListener implements View.OnClickListener {

    private int correctButtonId;

    public YourListener(int correctButtonId) {
        this.correctButtonId = correctButtonId;
    }

   @Override
    public void onClick(View v) {
        if (v.getId() == correctButtonId) {
            // do stuff
        } else {
            // do other stuff
        }
    }
}

然后,您可以将所有n按钮设置为具有此侦听器,并且可以从侦听器外部根据需要设置正确按钮的 id。

// this is the id of the button that is correct, where x represents its index, which you know ahead of time
int id = answerButtons[x].getId();

for (int i = 0; i < 4; i++) {
     answerButtons[i].setOnClickListener(new YourListener(id));
}

编辑回答:如何correctDialog从侦听器内部调用方法(例如,在您的情况下)。

一种方法是使侦听器成为您活动中的内部类。所以你有一些东西(未经测试,试一试),比如:

public class MainActivity extends AppCompatActivity {

    private class YourListener implements View.OnClickListener {
        private TextView textView;
        private Button[] buttons;
        private int correctButtonId;
        public YourListener(TextView textView, Button[] buttons, int correctButtonId) {
            this.textView = textView;
            this.buttons = buttons;
            this.correctButtonId = correctButtonId;
        }

        @Override
        public void onClick(View v) {
            if (v.getId() == correctButtonId) {
                MainActivity.this.correctDialog(textView, buttons);
            } else {
                MainActivity.this.wrongDialog(textView, buttons);
            }
        }
    }
}

推荐阅读