在Android的Recycler视图中选择Radio组中的单选按钮?

时间:2016-05-03 10:36:37

标签: android radio-button android-recyclerview radio-group recycler-adapter

我有带有无线电组及其4个单选按钮的Recycler视图。但是当我向下滚动列表时,项目的中间部分就像第一个一样。意味着如果我有10个项目,如果选择第一个项目按钮,那么6个按钮也可以选择用户选择。

如何处理回收站视图中的问题。任何建议都会很明显。 在此先感谢。

enter code here 
 public class ViewHolder extends RecyclerView.ViewHolder {
    TextView quest, timestamp, answer;
    RadioGroup rg;
    RadioButton rb1, rb2, rb3, rb4;
    Button submit;
    public ViewHolder(View view) {
        super(view);
        quest = (TextView) itemView.findViewById(R.id.ques);
        timestamp = (TextView) itemView.findViewById(R.id.tym);
        answer = (TextView) itemView.findViewById(R.id.answer);
        rb1 = (RadioButton)itemView.findViewById(R.id.rb1);
        rb2 = (RadioButton)itemView.findViewById(R.id.rb2);
        rb3 = (RadioButton)itemView.findViewById(R.id.rb3);
        rb4 = (RadioButton)itemView.findViewById(R.id.rb4);
        rb4 = (RadioButton)itemView.findViewById(R.id.rb4);
        rg = (RadioGroup)itemView.findViewById(R.id.radio);
        submit = (Button)itemView.findViewById(R.id.submit);


        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                int radioButtonID = group.getCheckedRadioButtonId();
                View radioButton = group.findViewById(radioButtonID);
                int clickedPos= (int) group.getTag();
                Log.v("currentpos",""+clickedPos);
                messageArrayList.get(clickedPos).setSelectedRadioButtonId(checkedId);
                int radioId = group.indexOfChild(radioButton);
                RadioButton btn = (RadioButton) group.getChildAt(radioId);
                final int currentPosition = getAdapterPosition();
                if (messageArrayList.get(clickedPos).getSelectedRadioButtonId() != -1 && checkedId != -1) {
                    try {

                        String selection = btn.getText().toString();
                        if (selection.equalsIgnoreCase(messageArrayList.get(clickedPos).getAnswer().toString())) {
                            Log.v("TAG", "USER OPTION" + "\t" + selection + "\n" + "CORRECT ANSWER IS" + "\t" + messageArrayList.get(clickedPos).getAnswer());
                           // rg.setVisibility(View.INVISIBLE);
                          //  answer.setVisibility(View.VISIBLE);
                           // answer.setText("Congrats, you are right. The answer is  " + messageArrayList.get(clickedPos).getAnswer().toString());


                     Toast.makeText(group.getContext(), "YOu are Right", Toast.LENGTH_SHORT).show();
                    } else {
                            // rg.setVisibility(View.INVISIBLE);
                            // answer.setVisibility(View.VISIBLE);
                            // answer.setText("Oops, you're wrong, the correct answer is  " + messageArrayList.get(clickedPos).getAnswer().toString());

                            Toast.makeText(group.getContext(), "You are Worng", Toast.LENGTH_SHORT).show();
                        }
                        Log.v("hello", selection);
                        String qusnn = quest.getText().toString();
                        Log.v("question", qusnn);
                        String read = "1";
                        try {
                            helper = new DBHelper(group.getContext());
                            database = helper.getWritableDatabase();
                            statement = database.compileStatement("update quiz set USERANS =? where QUESTION ='" + qusnn + "'");
                            statement.bindString(1, read);
                            statement.executeInsert();
                            database.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                            System.out.println("exception for send data in  table");
                        } finally {
                            database.close();
                        }

                    } catch (Exception e) {
                        StringWriter sw = new StringWriter();
                        e.printStackTrace(new PrintWriter(sw));
                        String exceptionAsString = sw.toString();
                        Log.v("hello", exceptionAsString);
                    }
                    Log.v("hello" + clickedPos, messageArrayList.get(clickedPos).getSelectedRadioButtonId() + "");


                }

            }});

    }
}


public ChatRoomThreadAdapter( ArrayList<Message> messageArrayList) {

    this.messageArrayList = messageArrayList;

    Calendar calendar = Calendar.getInstance();
    today = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView;
    if (viewType == SELF) {

        itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.recycler_items, parent, false);
    }else{

        itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.secondlayout, parent, false);
    }


    return new ViewHolder(itemView);
}

@Override
public int getItemViewType(int position) {
    Message message = messageArrayList.get(position);
    if (message.getUsans().equals("0")) {
        return SELF;
    }

    return position;
}

@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder,final int position) {
 final   Message message = messageArrayList.get(position);
    ((ViewHolder) holder).quest.setText(message.getMessage());
    ((ViewHolder) holder).rb1.setText(message.getOpt1());
    ((ViewHolder) holder).rb2.setText(message.getOpt2());
    ((ViewHolder) holder).rb3.setText(message.getOpt3());
    ((ViewHolder) holder).rb4.setText(message.getOpt4());
    ((ViewHolder) holder).answer.setText(message.getAnswer());
     String timestam= getTimeStamp(message.getCreatedAt());
    ((ViewHolder) holder).timestamp.setText(timestam);
   // ((ViewHolder) holder).rg.clearCheck();
  //  ((ViewHolder) holder).rg.setTag(position);
   // Log.e("select" + position, messageArrayList.get(position).getSelectedRadioButtonId() + "");

    ((ViewHolder) holder).rg.setTag(position);
    if (message.getSelectedRadioButtonId()!= -1){

        ((ViewHolder) holder).rg.check(message.getSelectedRadioButtonId());


    }else{
        //your always need to write else condition
        ((ViewHolder) holder).rg.clearCheck();
    }

}

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


public static String getTimeStamp(String dateStr) {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String timestamp = "";

    today = today.length() < 2 ? "0" + today : today;

    try {
        Date date = format.parse(dateStr);
        SimpleDateFormat todayFormat = new SimpleDateFormat("dd");
        String dateToday = todayFormat.format(date);
        format = dateToday.equals(today) ? new SimpleDateFormat("hh:mm a") : new SimpleDateFormat("dd LLL, hh:mm a");
        String date1 = format.format(date);
        timestamp = date1.toString();
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return timestamp;
}

}

enter code here

      public class Message implements Serializable {
String id, message, opt1, opt2, opt3, opt4, answer, createdAt,usans;


public Message() {
}

public Message(String id, String message, String opt1, String opt2, String opt3, String opt4, String answer, String createdAt,String usans) {
    this.id = id;
    this.message = message;
    this.opt1 = opt1;
    this.opt2 = opt2;
    this.opt3 = opt3;
    this.opt4 = opt4;
    this.answer = answer;
    this.createdAt = createdAt;
    this.usans = usans;
}
private int checkedId = -1;

public int getSelectedRadioButtonId() {
    return checkedId;
}

public void setSelectedRadioButtonId(int checkedId) {
    this.checkedId = checkedId;
}

public String getUsans() {
    return usans;
}

public void setUsans(String usans) {
    this.usans = usans;
}
public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public void setOpt1(String opt1) {
    this.opt1 = opt1;
}

public String getOpt1() {
    return opt1;
}

public void setOpt2(String opt2) {
    this.opt2 = opt2;
}

public String getOpt2() {
    return opt2;
}

public void setOpt3(String opt3) {
    this.opt3 = opt3;
}

public String getOpt3() {
    return opt3;
}

public void setOpt4(String opt4) {
    this.opt4 = opt4;
}

public String getOpt4() {
    return opt4;
}

public void setAnswer(String answer) {
    this.answer = answer;
}

public String getAnswer() {
    return answer;
}

public String getMessage() {
    return message;
}

public void setMessage(String message) {
    this.message = message;
}

public String getCreatedAt() {
    return createdAt;
}

public void setCreatedAt(String createdAt) {
    this.createdAt = createdAt;
}

}                                  

2 个答案:

答案 0 :(得分:0)

查看你的代码和评论我想你知道RecyclerView如何工作,尤其是重用视图..你唯一遗漏的是在所有场景中设置视图状态,我的意思是 - 你总是需要写 else部分代码

class MyViewHolder extends RecyclerView.ViewHolder {
            RadioGroup vRadioGroup;

            public MyViewHolder(View itemView) {
                super(itemView);
                vRadioGroup = (RadioGroup) itemView.findViewById(R.id.group1);
                //your other stuff
                vRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(RadioGroup radioGroup, int i) {
                        int clickedPos= (int) radioGroup.getTag();
                        messageArrayList.get(clickedPos).setSelectedRadioButtonId(radioButtonID);
                    }
                });
            }
 }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

                Message message = messageArrayList.get(position);

                //your other stuff
                holder.vRadioGroup.setTag(position);
                if (message.getSelectedRadioButtonId()!= -1){
                    holder.vRadioGroup.check(message.getSelectedRadioButtonId());
                }else{
                    //your always need to write else condition 
                    holder.vRadioGroup.clearCheck();
                }

        }

希望这会有所帮助..

答案 1 :(得分:0)

将此内容写入适配器类的onBindViewHolder():

holder.setIsRecyclable(假);

我遇到了同样的问题,添加此代码对我有帮助。

编辑:问题是由于当我们在Recycler View中滚动时,单元格被回收并且为了确保单元格不被回收,使用上述方法。