Android问答游戏:选中错误答案时如何高亮正确答案为绿色
解决Android问答游戏错误答案选中后正确答案不高亮的问题
修改后的answerSelected方法实现
假设你的答案选项是TextView类型,且已通过变量或列表持有这些控件引用,同时有correctAnswer变量存储当前题目的正确答案内容,以下是修改后的核心代码:
public void answerSelected(View view) { // 禁用所有答案选项的点击事件,防止重复选择 disableAllAnswerOptions(); String selectedAnswer = (String) view.getTag(); // 假设XML中给每个选项设置了android:tag="答案内容" TextView selectedTv = (TextView) view; if (!selectedAnswer.equals(correctAnswer)) { // 选中错误答案:设置为红色 selectedTv.setTextColor(getResources().getColor(R.color.red)); // 遍历所有答案选项,找到正确答案并设置为绿色 for (TextView optionTv : answerOptionList) { // answerOptionList是存储所有选项TextView的列表 if (correctAnswer.equals(optionTv.getTag())) { optionTv.setTextColor(getResources().getColor(R.color.green)); break; } } } else { // 选中正确答案:直接设置为绿色 selectedTv.setTextColor(getResources().getColor(R.color.green)); } } // 辅助方法:禁用所有答案选项的点击 private void disableAllAnswerOptions() { for (TextView optionTv : answerOptionList) { optionTv.setClickable(false); } }
关键说明
- XML布局配合:确保每个答案选项的
TextView添加android:tag属性,值为该选项对应的答案文本,方便快速匹配正确答案:
<TextView android:id="@+id/tv_option1" android:layout_width="match_parent" android:layout_height="wrap_content" android:tag="选项1内容" android:clickable="true" android:onClick="answerSelected" ... />
- 颜色资源配置:在
res/values/colors.xml中定义红色和绿色:
<color name="red">#FF0000</color> <color name="green">#00FF00</color>
- 控件引用管理:提前将所有答案选项的
TextView存入answerOptionList列表(可在onCreate方法中初始化),便于遍历查找正确答案。
内容的提问来源于stack exchange,提问作者ItzBaturalp Plays
相关产品推荐
相关产品推荐

