В обзоре утилит, как определить, нажата ли кнопка переключателя, из той же группы радио в Android - PullRequest
0 голосов
/ 01 января 2019

У меня есть RadioGroup с 4 RadioButtons внутри RecyclerView.Адаптер RecyclerView выглядит следующим образом:

    class QuestionRecyclerAdapter(var number:Int, val context: Context, val quesions: List<Question>,val qnADao: QnADao) : RecyclerView.Adapter<QuestionRecyclerAdapter.ViewHolder>() {
        lateinit var question:Question
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {

            return ViewHolder(LayoutInflater.from(context).inflate(R.layout.question_single_item, parent, false));
        }

        override fun getItemCount(): Int {

            return quesions.size;
        }
         fun updateNumber(number: Int){
            this.number = number
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {

            question = quesions[position]
            holder.textTestQuestion.text = ""+(number+position)+" "+ question.question;
            holder.answerFirst.text = "a. "+ question.answers?.get(0).toString()
            holder.answerSecond.text = "b. "+ question.answers?.get(1).toString()
            holder.answerThird.text = "c. "+ question.answers?.get(2).toString()
            holder.answerFourth.text = "d. "+ question.answers?.get(3).toString()   

            holder.radio_group.setOnCheckedChangeListener(object : RadioGroup.OnCheckedChangeListener{
                override fun onCheckedChanged(group: RadioGroup?, checkedId: Int) {
                    when(checkedId){
                        R.id.answerFirst -> {
                            question.rightAnswer=0
                        }
                        R.id.answerSecond -> {
                            question.rightAnswer=1
                        }
                        R.id.answerThird -> {
                            question.rightAnswer=2
                        }
                        R.id.answerFourth -> {
                            question.rightAnswer=3
                        }
                    }

        }


        class ViewHolder(view: View) : RecyclerView.ViewHolder(view)  {
            val textTestQuestion = view.test_text_question
            val answerFirst = view.answerFirst
            val answerSecond = view.answerSecond
            val answerThird = view.answerThird
            val answerFourth = view.answerFourth
            val radio_group = view.radioGrp


        }
    }

question_single_item.xml выглядит так:

        <RadioButton
            android:id="@+id/first"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:button="@null"
            android:checked="false"
            android:drawableRight="@android:drawable/btn_radio"
            android:textSize="14dp" />

        <RadioButton
            android:id="@+id/second"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:button="@null"
            android:checked="false"
            android:drawableRight="@android:drawable/btn_radio"
            android:textSize="14dp" />

        <RadioButton
            android:id="@+id/third"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:button="@null"
            android:checked="false"
            android:drawableRight="@android:drawable/btn_radio"
            android:textSize="14dp" />

        <RadioButton
            android:id="@+id/fourth"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:button="@null"
            android:checked="false"
            android:drawableRight="@android:drawable/btn_radio"
            android:textSize="14dp" />
    </RadioGroup>
</RelativeLayout>

В представлении реселлера я заполняю почти 100 сек данных, поэтому существует 100 радиогрупп со 100 * 4.Радио-кнопки.Поэтому мне нужно выяснить, выбраны ли одинаковые радиокнопки в одной радиогруппе или нет.Другими словами, мне нужно выяснить, выбран ли переключатель (4 в группе) из той же группы или нет.Любая помощь будет оценена.Спасибо

1 Ответ

0 голосов
/ 02 января 2019

вы должны использовать хеш-карту от имени каждого щелчка переключателя в одной и той же группе радиостанций. Эта проблема в основном из-за повторного использования вашего объекта Adapter.

Итак, вы должны сохранитьвыбранный элемент, как и вам следует проверять и обновлять, когда бы он ни вызывал метод getView в представлении.

вот код для ссылки: пожалуйста, следуйте и дайте мне знать:

открытый класс CustomArrayAdapterрасширяет BaseAdapter {

private Context context;
private ArrayList<HashMap<String, String>> data;

public CustomArrayAdapter(Context context,ArrayList<HashMap<String, String>> data) {
    super();
    this.context = context;
    this.data = data;

}

public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if(convertView==null){
        holder = new ViewHolder();
        convertView = LayoutInflater.from(context).inflate(R.layout.custom_questions, parent,false);
        holder.textView1 = (TextView) convertView.findViewById(R.id.textView1);
        holder.radioGroup1 = (RadioGroup) convertView.findViewById(R.id.radioGroup1);
        holder.radio0 = (RadioButton) convertView.findViewById(R.id.radio0);
        holder.radio1 = (RadioButton) convertView.findViewById(R.id.radio1);
        holder.radio2 = (RadioButton) convertView.findViewById(R.id.radio2);
        holder.radio3 = (RadioButton) convertView.findViewById(R.id.radio3);

        convertView.setTag(holder);
    }else{
        holder =(ViewHolder) convertView.getTag();
    }

    holder.textView1.setText(data.get(position).get("questions"));
    holder.radio0.setText(data.get(position).get("op1"));
    holder.radio1.setText(data.get(position).get("op2"));
    holder.radio2.setText(data.get(position).get("op3"));
    holder.radio3.setText(data.get(position).get("op4"));

    HashMap<Integer,String> radioMap = new HashMap<Integer, String>();
    radioMap.put(holder.radio0.getId(),holder.radio0.getText().toString());
    radioMap.put(holder.radio1.getId(),holder.radio1.getText().toString());
    radioMap.put(holder.radio2.getId(),holder.radio2.getText().toString());
    radioMap.put(holder.radio3.getId(),holder.radio3.getText().toString());

    holder.radioGroup1.setTag(radioMap);
    holder.radioGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            HashMap<Integer,String> data = (HashMap<Integer,String>) group.getTag();
            Toast.makeText(context,data.get(checkedId),Toast.LENGTH_SHORT).show();
        }
    });

    return convertView;
}

@Override
public int getCount() {
    return data.size();
}

@Override
public Object getItem(int position) {
    return data.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

class ViewHolder{
    TextView textView1;
    RadioGroup radioGroup1;
    RadioButton radio0;
    RadioButton radio1;
    RadioButton radio2;
    RadioButton radio3;
}

}

...