简体   繁体   English

RadioGroup 中的 RecyclerView 和 RadioButton

[英]RecyclerView And RadioButton in RadioGroup

I have RecyclerView and in the RowItem layout I have RadioGroup and in them, I Have Two RadioButton.我有 RecyclerView,在 RowItem 布局中,我有 RadioGroup,其中有两个 RadioButton。 if I select First Item and scroll to the bottom, the 8th, 16th,... so checked:|如果我选择 First Item 并滚动到底部,第 8 个,第 16 个,...所以检查:| How handle it?怎么处理?

tnx for the answer .. if you need any info .. I put the theme tnx的答案..如果你需要任何信息..我把主题

ques_item_row.xml ques_item_row.xml

 <RadioGroup
                    android:id="@+id/ques_radio_group"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/txt_ques_title"
                    android:layout_gravity="end|center"
                    android:gravity="start"
                    android:orientation="vertical"
                    android:textAlignment="textStart"
                    android:textDirection="rtl">

                    <android.support.v7.widget.AppCompatRadioButton
                        android:id="@+id/first_ques"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_gravity="end|right"
                        android:layout_margin="@dimen/quest_margin"
                        android:gravity="end|right"
                        android:checked="false"
                        android:padding="@dimen/quest_padding"
                        android:text="@{question.firstQuest}"
                        android:textColor="@color/ques"
                        android:textDirection="ltr"
                        android:textSize="@dimen/text_ques"
                        />

                    <android.support.v7.widget.AppCompatRadioButton
                        android:id="@+id/second_ques"
                        android:layout_below="@+id/first_ques"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_gravity="end|right"
                        android:layout_margin="@dimen/quest_margin"
                        android:gravity="end|right"
                        android:checked="false"
                        android:padding="@dimen/quest_padding"
                        android:text="@{question.secondQuest}"
                        android:textColor="@color/ques"
                        android:textDirection="ltr"
                        android:textSize="@dimen/text_ques"
                        />


                </RadioGroup>

Question.java问题.java

public class Question {

  private String questNum;
  private String questTitle;
  private String firstQuest;
  private String secondQuest;
  private int score = 0;
  private int firstQuestScore = 2;
  private int secondQuestScore = 3;

  private boolean isFirstChecked;
  private boolean isSecondChecked;


  public Question(String questNum, String questTitle, String firstQuest, String secondQuest) {
    this.questTitle = questTitle;
    this.firstQuest = firstQuest;
    this.secondQuest = secondQuest;
    this.questNum = questNum;

  }

  public Question() {

  }


  public String getQuestTitle() {
    return questTitle;
  }

  public void setQuestTitle(String questTitle) {
    this.questTitle = questTitle;
  }

  public String getFirstQuest() {
    return firstQuest;
  }

  public void setFirstQuest(String firstQuest) {
    this.firstQuest = firstQuest;
  }

  public String getSecondQuest() {
    return secondQuest;
  }

  public void setSecondQuest(String secondQuest) {
    this.secondQuest = secondQuest;
  }

  public String getQuestNum() {
    return questNum;
  }

  public void setQuestNum(String questNum) {
    this.questNum = questNum;
  }

  public boolean isFirstChecked() {
    return isFirstChecked;
  }

  public void setFirstChecked(boolean firstChecked) {
    isFirstChecked = firstChecked;
  }

  public boolean isSecondChecked() {
    return isSecondChecked;
  }

  public void setSecondChecked(boolean secondChecked) {
    isSecondChecked = secondChecked;
  }

  public int getScore() {
    return score;
  }

  public void setScore(int questNum, int questScore) {
    this.score = ((questNum * questScore) + questNum);
  }


  public int getFirstQuestScore() {
    return firstQuestScore;
  }

  public void setFirstQuestScore(int firstQuestScore) {
    this.firstQuestScore = firstQuestScore;
  }

  public int getSecondQuestScore() {
    return secondQuestScore;
  }

  public void setSecondQuestScore(int secondQuestScore) {
    this.secondQuestScore = secondQuestScore;
  }


  public void mathScore(int questNum, int questScore) {
  }
}

QuestionAdapter.java问题适配器.java

 public class MbtiQuestAdapter extends RecyclerView.Adapter<MbtiQuestAdapter.MbtiQuestViewHolder> {

  private Context context;
  private List<Question> questionList;
  private LayoutInflater layoutInflater;
  private FloatingActionButton fabResult;
  private CoordinatorLayout coordinator;
  private int checkRadio = 0;
  private Snackbar snackbar;
  private int totalScore = 0;


  private static final String TAG = "MbtiQuestAdapter";

  public MbtiQuestAdapter(Context context, List<Question> questionList, FloatingActionButton fab, CoordinatorLayout coordinator) {
    this.context = context;
    this.questionList = questionList;
    this.fabResult = fab;
    this.coordinator = coordinator;
  }


  @NonNull
  @Override
  public MbtiQuestViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    if (layoutInflater == null) {
      layoutInflater = LayoutInflater.from(context);
    }

    QuesItemRowBinding binding = DataBindingUtil.inflate(layoutInflater,
      R.layout.ques_item_row, parent, false);

    return new MbtiQuestViewHolder(binding);
  }


  @Override
  public void onBindViewHolder(@NonNull final MbtiQuestViewHolder holder, final int position) {

    final Question question = questionList.get(position);
    holder.binding.setQuestion(question);

    //Fix the select the radio Button when first Select 8th and... do not selected



    //************************************************************


    //Check if all question do not click do not allow go to the next page

    holder.binding.quesRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
      @Override
      public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (holder.binding.firstQues.isChecked() || holder.binding.secondQues.isChecked()) {
          checkRadio++;

        } else {
//          snackbar = Snackbar.make(coordinator, R.string.choose_one_of_theme, Snackbar.LENGTH_INDEFINITE);
//          snackbar.show();
        }
      }
    });



   if (fabResult != null) {
      fabResult.setOnClickListener(new View.OnClickListener() {
                                     @Override
                                     public void onClick(View v) {
                                       if (checkRadio == 60) {
                                         context.startActivity(new Intent(context, ResultActivity.class));

                                         totalScore = 0;
                                         for (int i = 0; i < 60; i++) {
                                           totalScore = totalScore + question.getScore();
                                           Log.i(TAG, "TotalScore: " + totalScore);
                                         }


                                         switch (totalScore) {
                                         }

                                       } else {
                                         snackbar = Snackbar.make(coordinator, R.string.check_all_ques_err, Snackbar.LENGTH_SHORT);
                                         snackbar.show();


                                       }
                                     }
                                   }

      );

      //*************************************************************



    }
  }


  @Override
  public int getItemCount() {
    return questionList.size();
  }

  public class MbtiQuestViewHolder extends RecyclerView.ViewHolder {

    private QuesItemRowBinding binding;

    public MbtiQuestViewHolder(QuesItemRowBinding binding) {
      super(binding.getRoot());
      this.binding = binding;

    }
  }


}

please help me .. I add some screenshot too ... tnx a lot请帮帮我..我也添加了一些截图...... tnx很多

I tried this code but not worked:我试过这段代码但没有奏效:

holder.binding.firstQues.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {

        question.setFirstChecked(holder.binding.firstQues.isChecked());
        holder.binding.firstQues.setChecked(holder.binding.firstQues.isChecked());

        question.setSecondChecked(false);
        holder.binding.secondQues.setChecked(false);
      }
    });

    holder.binding.secondQues.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {

        question.setFirstChecked(false);
        holder.binding.firstQues.setChecked(false);

        question.setSecondChecked(holder.binding.secondQues.isChecked());
        holder.binding.secondQues.setChecked(holder.binding.secondQues.isChecked());
      }
    });

    holder.binding.firstQues.setChecked(question.isFirstChecked());
    holder.binding.secondQues.setChecked(question.isSecondChecked());

在此处输入图片说明

在此处输入图片说明

You have to hold selected radio button id to your model.您必须将选定的单选按钮 ID 保留到您的模型中。

1> Take selectedId in your model. 1> 在你的模型中选择 selectedId。

class Model{
  int selctedId;
  // getter setter
}

2> Attach this id to your radio group. 2> 将此 ID 附加到您的无线电组。

@Override
public void onBindViewHolder(final CoachListViewHolder holder, final int position) {
    Model model = list.get(position);
    holder.radioGroup.check(model.getSelectedId);
    holder.radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
    {
        public void onCheckedChanged(RadioGroup group, int checkedId)
        {
         model.setSelectedId(checkedId);
        }
    });

In this solution we hold selected id in model, and we attach back this field to radio group by radioGroup.check(model.getSelectedId);在这个解决方案中,我们在模型中保存选定的 id,我们通过radioGroup.check(model.getSelectedId);将此字段附加到无线电组radioGroup.check(model.getSelectedId);

Reason原因

When you don't hold your selected value, then it is recycled when user scrolls position.当您不保留所选值时,它会在用户滚动位置时被回收。

I found a related question also.我也发现了一个相关的问题

Well Tested Solution久经考验的解决方案

You are using data binding, so above solution can be more short.您正在使用数据绑定,因此上述解决方案可以更短。 Use two-way binding to hold selected id.使用双向绑定来保存选定的 id。

Item.java项目.java

public class Item extends BaseObservable{
    private int selectedId;

    public int getSelectedId() {
        return selectedId;
    }

    public void setSelectedId(int selectedId) {
        this.selectedId = selectedId;
    }
}

row_list.xml行列表.xml

<data>

    <variable
        name="item"
        type="com.innovanathinklabs.sample.ui2.Item"/>

</data>

<RadioGroup
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="20dp"
    android:background="@color/colorPrimary"
    android:checkedButton="@={item.selectedId}"
    >

    <android.support.v7.widget.AppCompatRadioButton
        android:id="@+id/rbMale"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="male"/>

    <android.support.v7.widget.AppCompatRadioButton
        android:id="@+id/rbFemale"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="female"/>
</RadioGroup>

Now when you need to get selected item.现在,当您需要获取所选项目时。 Then do this.然后这样做。

if(list.get(1).getSelectedId() == R.id.rbMale){
 // male is selected
}
else if (list.get(1).getSelectedId() == R.id.rbMale){
 // female is selcted
}

Also remove any other unnecessary logics from Radio group and Radio buttons.同时从 Radio 组和 Radio 按钮中删除任何其他不必要的逻辑。

Data binding magic is数据绑定魔法是

This code is converted to android:checkedButton="@={item.selectedId}"此代码转换为android:checkedButton="@={item.selectedId}"

 
 
 
  
  @Override public void onBindViewHolder(final CoachListViewHolder holder, final int position) { Model model = list.get(position); holder.radioGroup.check(model.getSelectedId); holder.radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { public void onCheckedChanged(RadioGroup group, int checkedId) { model.setSelectedId(checkedId); } });
 
 

Update更新

This is how you bind your item in your item layout.这就是您在项目布局中绑定项目的方式。

holder.binding.setItem(list.get(position));

Add private int isFirstQuestionChecked = false to your model and change it whenever you select this RadioButton .private int isFirstQuestionChecked = false添加到您的模型中,并在您选择此RadioButton时更改它。 In your adapter show proper value for RadioButton在您的适配器中显示RadioButton正确值

if (element.isFirstQuestionChecked == true) {
    selectRadioButton()
} else {
    deselectRadioButton() // it's important!
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM