java - 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);
}
});
}
}
解决方案
创建一个通用侦听器,您可以将其添加到所有按钮中,并在该侦听器中处理用于根据需要确定哪个是正确的逻辑。例如:
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);
}
}
}
}
推荐阅读
- javascript - 根据选择选项添加按钮以显示隐藏?
- python - 逆矩阵结果在 MATLAB 和 Python 中不同
- laravel - 通过 .htaccess / 异常管理位置 / 框架 Laravel 重定向到安全连接
- c# - 在 C# 中使用 Git TFS API 在一次提交中进行移动和编辑?
- stanford-nlp - 如何从文件中读取规则
- android - 如何将 Android Studio 项目导出到特定存储库中的新 GitHub 分支?
- java - 无法将功能作为内容添加到 Vogella Eclipse RCP 教程项目
- javascript - 为什么没有导入文件 - 用 Jest 测试 VueJS
- python - 如何 pip 卸载使用 git 项目 URL 安装的包?
- vba - Excel VBA/公式。用当月的每个星期五填充一系列单元格