在一个Activity中循环使用一组RadioGroup

一个activity是用来做题用的,效果如下图

在点击下一题时,RadioGroup会默认为第一次选中的状态,造成RadioButton选择混。

解决方案: 第一步:取消监听 radioGroup_problem_group.setOnCheckedChangeListener(null)radioGroup_problem_group为RadioGroup变量名。

                  第二部:清除选中记录 radioGroup_problem_group.clearCheck();

主要代码:

1. 布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!--单选题-->
    <LinearLayout
        android:id="@+id/linearLayout_problem"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:visibility="visible"
        >

        <!--题目标题-->
        <LinearLayout
            android:id="@+id/linearLayout_problem_problem"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            >

            <!--选择题目题号-->
            <TextView
                android:id="@+id/textView_problem_number"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"

                />

            <!--选择题目标题-->
            <TextView
                android:id="@+id/textView_problem_title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                />

        </LinearLayout>

        <!--题目选项-->
        <LinearLayout
            android:id="@+id/linearLayout_problem_checkBox"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:layout_marginLeft="5dp"
            >

            <!--选项单选-->
            <RadioGroup
                android:id="@+id/radioGroup_problem_group"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                >

                <!--题目选项1  android:background="@drawable/linear_layout_middle_content" -->
                <RadioButton
                    android:id="@+id/radioButton_problem_option1"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"


                    />

                <!--题目选项2-->
                <RadioButton
                    android:id="@+id/radioButton_problem_option2"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="20dp"


                    />

                <!--题目选项3-->
                <RadioButton
                    android:id="@+id/radioButton_problem_option3"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="20dp"


                    />

                <!--题目选项4-->
                <RadioButton
                    android:id="@+id/radioButton_problem_option4"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="20dp"


                    />
            </RadioGroup>

        </LinearLayout>

    </LinearLayout>

    <!--显示已答和总题数信息-->
    <LinearLayout
        android:id="@+id/linearLayout_problem_information"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:visibility="visible"
        >

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="match_parent">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="已答/总数 :  "
                />

            <TextView
                android:id="@+id/textView_problem_answered_total"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=" / "
                />

            <TextView
                android:id="@+id/textView_problem_all_total"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                />

        </LinearLayout>

    </LinearLayout>


    <!--下一题按钮-->
    <Button
        android:id="@+id/button_problem_next"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:background="@drawable/linear_layout_middle_content"
        android:visibility="gone"
        android:text="下一题"
        />

    <!--完成按钮-->
    <Button
        android:id="@+id/button_problem_complete"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:background="@drawable/linear_layout_middle_content"
        android:visibility="gone"
        android:text="完成"
        />

</LinearLayout>

2. activity代码

package com.example.lenovo.computerbase;

import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.example.lenovo.computerbase.bean.HttpAddress;
import com.example.lenovo.computerbase.bean.Problem;
import com.example.lenovo.computerbase.bean.ShowToast;
import com.example.lenovo.computerbase.controller.ActivityCollectorController;
import com.example.lenovo.computerbase.http.HttpConnection;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Response;

/*
*  测试练习
* */
public class TestActivity extends AppCompatActivity implements View.OnClickListener{

    //返回和退出布局LinearLayout
    private LinearLayout linearLayout_title_back,linearLayout_title_close;
    //返回和退出布局ImageView
    private ImageView imageView_title_back, imageView_title_close;
    //顶部中间显示文字区域
    private TextView textView_title_text;

    private TextView textView_problem_number, textView_problem_title;
    private RadioGroup radioGroup_problem_group;
    private RadioButton radioButton_problem_option1, radioButton_problem_option2,
            radioButton_problem_option3, radioButton_problem_option4;
    private TextView textView_problem_answered_total, textView_problem_all_total;
    private Button button_problem_next, button_problem_complete;

    private ProblemHandler problemHandler = new ProblemHandler(this);

    HttpAddress httpAddress = new HttpAddress();
    private String loginId;

    private int index = 0;
    ArrayList<Problem> problems = new ArrayList<>();
    private int length;
    private int textColor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);

        httpAddress = (HttpAddress) getApplication();
        loginId = getIntent().getStringExtra("loginId");
        initView();

        requestProblem();

    }

    public void initView(){
        //将该Activity加入活动集合控制器
        ActivityCollectorController.addActivity(this);

        //将导航栏隐藏
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null){
            actionBar.hide();
        }

        //返回
        linearLayout_title_back = (LinearLayout)findViewById(R.id.linearLayout_title_back);
        linearLayout_title_back.setOnClickListener(this);

        //退出
        linearLayout_title_close = (LinearLayout)findViewById(R.id.linearLayout_title_close);
        linearLayout_title_close.setOnClickListener(this);

        //返回和退出布局ImageView
        imageView_title_back = (ImageView)findViewById(R.id.imageView_title_back);
        imageView_title_back.setColorFilter(this.getResources().getColor(R.color.colorWhite));
        imageView_title_close = (ImageView)findViewById(R.id.imageView_title_close);
        imageView_title_close.setColorFilter(this.getResources().getColor(R.color.colorWhite));

        //顶部中间显示文字区域
        textView_title_text = (TextView)findViewById(R.id.textView_title_text);
        textView_title_text.setText("随机练习");
        textView_title_text.setTextColor(this.getResources().getColor(R.color.colorWhite));

        textView_problem_number = (TextView) findViewById(R.id.textView_problem_number);
        textView_problem_title = (TextView) findViewById(R.id.textView_problem_title);

        radioGroup_problem_group = (RadioGroup) findViewById(R.id.radioGroup_problem_group);

        radioButton_problem_option1 = (RadioButton) findViewById(R.id.radioButton_problem_option1);
        radioButton_problem_option2 = (RadioButton) findViewById(R.id.radioButton_problem_option2);
        radioButton_problem_option3 = (RadioButton) findViewById(R.id.radioButton_problem_option3);
        radioButton_problem_option4 = (RadioButton) findViewById(R.id.radioButton_problem_option4);
        /* 得到RadioButton文字显示的默认颜色(黑色)
        * */
        textColor = radioButton_problem_option1.getCurrentTextColor();

        textView_problem_answered_total = (TextView) findViewById(R.id.textView_problem_answered_total);
        textView_problem_all_total = (TextView) findViewById(R.id.textView_problem_all_total);

        button_problem_next = (Button) findViewById(R.id.button_problem_next);
        button_problem_next.setOnClickListener(this);
        button_problem_complete = (Button) findViewById(R.id.button_problem_complete);
        button_problem_complete.setOnClickListener(this);

    }

    private static class ProblemHandler extends Handler{
        private final WeakReference<TestActivity> weakReference;

        public ProblemHandler(TestActivity testActivity){
            weakReference = new WeakReference<>(testActivity);
        }

        @Override
        public void handleMessage(Message message){
            if (weakReference.get() == null)
                return;

            // something
            weakReference.get().problems = message.getData().getParcelableArrayList("problems");
            weakReference.get().length = weakReference.get().problems.size();
            weakReference.get().showProblems(weakReference.get().index);
        }
    }

  //进行网络请求
public void requestProblem(){ httpAddress.setAddress("RandomTestServlet"); HttpConnection.sendOkHttpRequest(httpAddress.getAddress(), new okhttp3.Callback(){ @Override public void onFailure(Call call, IOException e) { Log.d("TestActivity", "请求服务器失败!"); } @Override public void onResponse(Call call, Response response) throws IOException { String responseData = response.body().string(); System.out.println(responseData); ArrayList<Problem> problems = new Gson().fromJson(responseData, new TypeToken<ArrayList<Problem>>(){}.getType()); putProblemHandler(problems); } }); } public void putProblemHandler(ArrayList<Problem> problems){ Message message = Message.obtain(); Bundle bundle = new Bundle(); bundle.putParcelableArrayList("problems", problems); message.setData(bundle); problemHandler.sendMessage(message); }
  //通过下标取出单个Problem
public void showProblems(int index){ if (index < length){ showProblem(problems.get(index)); } }
  //在页面上显示题目信息
public void showProblem(Problem problem){ textView_problem_number.setText(String.valueOf(problem.getP_no())); textView_problem_title.setText(problem.getP_title()); radioButton_problem_option1.setText("A. " + problem.getP_option1()); radioButton_problem_option2.setText("B. " + problem.getP_option2()); radioButton_problem_option3.setText("C. " + problem.getP_option3()); radioButton_problem_option4.setText("D. " + problem.getP_option4()); /* 将RadioButton字体颜色设置为默认,是为了消除上一次选中留下的记录 * */ radioButton_problem_option1.setTextColor(textColor); radioButton_problem_option2.setTextColor(textColor); radioButton_problem_option3.setTextColor(textColor); radioButton_problem_option4.setTextColor(textColor);
    // 显示已答题数和全部题数
showAnsweredTotal(index, length); RadioGroupProblemListener radioGroupProblemListener = new RadioGroupProblemListener(problem);     //为RadioGroup设置监听 radioGroup_problem_group.setOnCheckedChangeListener(radioGroupProblemListener); } // 内部类(设置监听) class RadioGroupProblemListener implements RadioGroup.OnCheckedChangeListener{ private Problem problem; RadioGroupProblemListener(Problem problem){ this.problem = problem; } @Override public void onCheckedChanged(RadioGroup radioGroup, int id) { //选择选项1 if (id == radioButton_problem_option1.getId()) { /* 答案和选项1相等时,选项1显示GREEN颜色 否则,选项1显示RED颜色 并分别判断答案和其余每个选项是否相等,相等显示GREEN颜色 */ if (problem.getP_answer().equals(problem.getP_option1())){ radioButton_problem_option1.setTextColor(Color.GREEN); }else { radioButton_problem_option1.setTextColor(Color.RED); if (problem.getP_answer().equals(problem.getP_option2())){ radioButton_problem_option2.setTextColor(Color.GREEN); }else if (problem.getP_answer().equals(problem.getP_option3())){ radioButton_problem_option3.setTextColor(Color.GREEN); }else if (problem.getP_answer().equals(problem.getP_option4())){ radioButton_problem_option4.setTextColor(Color.GREEN); } } lastProblem(); } //选择选项2 else if (id == radioButton_problem_option2.getId()) { if (problem.getP_answer().equals(problem.getP_option2())){ radioButton_problem_option2.setTextColor(Color.GREEN); }else { radioButton_problem_option2.setTextColor(Color.RED); if (problem.getP_answer().equals(problem.getP_option1())){ radioButton_problem_option1.setTextColor(Color.GREEN); }else if (problem.getP_answer().equals(problem.getP_option3())){ radioButton_problem_option3.setTextColor(Color.GREEN); }else if (problem.getP_answer().equals(problem.getP_option4())){ radioButton_problem_option4.setTextColor(Color.GREEN); } } lastProblem(); } //选择选项3 else if (id == radioButton_problem_option3.getId()) { if (problem.getP_answer().equals(problem.getP_option3())){ radioButton_problem_option3.setTextColor(Color.GREEN); }else { radioButton_problem_option3.setTextColor(Color.RED); if (problem.getP_answer().equals(problem.getP_option1())){ radioButton_problem_option1.setTextColor(Color.GREEN); }else if (problem.getP_answer().equals(problem.getP_option2())){ radioButton_problem_option2.setTextColor(Color.GREEN); }else if (problem.getP_answer().equals(problem.getP_option4())){ radioButton_problem_option4.setTextColor(Color.GREEN); } } lastProblem(); } //选择选项4 else if (id == radioButton_problem_option4.getId()) { if (problem.getP_answer().equals(problem.getP_option4())){ radioButton_problem_option4.setTextColor(Color.GREEN); }else { radioButton_problem_option4.setTextColor(Color.RED); if (problem.getP_answer().equals(problem.getP_option1())){ radioButton_problem_option1.setTextColor(Color.GREEN); }else if (problem.getP_answer().equals(problem.getP_option2())){ radioButton_problem_option2.setTextColor(Color.GREEN); }else if (problem.getP_answer().equals(problem.getP_option3())){ radioButton_problem_option3.setTextColor(Color.GREEN); } } lastProblem(); } } }
   //判断是否最后一题,最后一题时显示完成按钮,否则显示下一题按钮
public void lastProblem(){ System.out.println("index = " + index); System.out.println("length = " + length); showAnsweredTotal(index + 1, length); // 最后一题 if (index == length - 1){ System.out.println("index == length - 1 "); button_problem_complete.setVisibility(View.VISIBLE); }else { System.out.println("index != length - 1 "); button_problem_next.setVisibility(View.VISIBLE); } } public void showAnsweredTotal(int i, int j){ // 已答题数 textView_problem_answered_total.setText(String.valueOf(i)); textView_problem_answered_total.setTextColor(Color.GREEN); // 全部题数 textView_problem_all_total.setText(String.valueOf(j)); } /* 设置恢复RadioGroup默认状态 * */ public void defaultRadioGroup(){ /* * 循环使用RadioGroup时需要先取消监听,再清除选中记录 * */ // 1. 取消监听 radioGroup_problem_group.setOnCheckedChangeListener(null); // 2. 清除选中记录 radioGroup_problem_group.clearCheck(); } @Override public void onClick(View view) { switch (view.getId()){ //返回 case R.id.linearLayout_title_back: finish(); break; //退出 case R.id.linearLayout_title_close: ActivityCollectorController.finishAll(); Intent closeIntent = new Intent(getBaseContext(),LoginActivity.class); startActivity(closeIntent); new ShowToast(this,"您已退出!").showToast(); break; case R.id.button_problem_next:           //题目索引加一 index ++; button_problem_next.setVisibility(View.GONE); // 清除上次选中记录 defaultRadioGroup(); showProblems(index); // 2. 重新请求problem break; case R.id.button_problem_complete: button_problem_complete.setVisibility(View.GONE); finish(); break; default: } } }
原文地址:https://www.cnblogs.com/xiaoxiaoyibu/p/8824609.html