Android RadioGroup動態添加RadioButton

import android.app.AppComponentFactory;
import android.content.Context;
import android.text.Html;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.fenbitou.kaoyanzhijia.combiz.utils.AppUtil;
import com.fenbitou.kaoyanzhijia.examination.R;
import com.fenbitou.kaoyanzhijia.examination.data.question.QuestionBean;


/**
 * author : liguangliang
 * date : 2020-01-26 13:57
 * description :單選題自定義view
 */
public class SingleChoiseView extends LinearLayout {

    private static final int ID_INIT=0xF0;

    private final RadioGroup rgAnswer;
    private final TextView tvQuestion;
    private OnAnswerSelectedListener mListener;

    public SingleChoiseView(Context context, AttributeSet attrs) {
        super(context, attrs);
        View view = LayoutInflater.from(context).inflate(R.layout.exam_view_choice_view, this);
        rgAnswer = view.findViewById(R.id.rg_answer);
        tvQuestion = view.findViewById(R.id.tv_question);

    }

    public void updateQuestionInfo(QuestionBean qst){

        if(qst!=null){
            tvQuestion.setText(Html.fromHtml(getContext().getResources().getString(R.string.exam_question_content_score,qst.getQstContent(),
                    AppUtil.formatDouble(qst.getScore()))));
            if(qst.getOptions()!=null && !qst.getOptions().isEmpty()){

                for (int i = 0; i < qst.getOptions().size(); i++) {
                    RadioButton button = LayoutInflater.from(getContext())
                            .inflate(R.layout.exam_view_single_choice, rgAnswer, false)
                            .findViewById(R.id.rb_answer);
                    button.setText(String.format("%s  %s",qst.getOptions().get(i).getOptOrder(),qst.getOptions().get(i).getOptContent()));
                    button.setId(ID_INIT+i);
                    rgAnswer.addView(button, i);
                    rgAnswer.setOnCheckedChangeListener((radioGroup, i1) -> {
                        Log.e("TAG", "onCheckedChanged: "+ i1);
                        mListener.onAnswerSelected(i1 ^ ID_INIT);
                    });
                }
            }

        }

    }


    public void setOnAnswerSelectedListener(OnAnswerSelectedListener mListener) {
        this.mListener = mListener;
    }

    public interface OnAnswerSelectedListener {
        void onAnswerSelected(int answer);
    }
}
發佈了206 篇原創文章 · 獲贊 68 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章