天字一号大盗
2020-06-16 18:21
采纳率: 100%
浏览 123

radiobutton的选中位置不变是怎么回事?

public class MyArrayAdapter extends ArrayAdapter {
    private Context context;
    private int resourceId;
    private HashMap<Integer, Boolean> ableChecked= new HashMap<>();
    private Address address;
    private List<Address> list;
    ViewHolder viewHolder=null;

    public MyArrayAdapter(@NonNull Context context, int resource, @NonNull List objects) {
        super(context, resource, objects);
        this.context = context;
        this.resourceId = resource;
        this.list = objects;
        for (int i = 0; i < list.size(); i++) {
            ableChecked.put(i, false);
        }
    }

    @Override
    public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
         address = list.get(position);
         if (convertView == null){
             convertView=View.inflate(context,resourceId,null);
             viewHolder = new ViewHolder();
             viewHolder.radioButton = convertView.findViewById(R.id.rb_select);
             viewHolder.textViewpath = convertView.findViewById(R.id.select_item);
             viewHolder.textViewpathname = convertView.findViewById(R.id.path);
             convertView.setTag(viewHolder);
         }
         else {
             viewHolder = (ViewHolder)convertView.getTag();
         }
         viewHolder.textViewpath.setText(address.getPath());
         viewHolder.textViewpathname.setText(address.getPathName());
//         viewHolder.radioButton.setChecked(ableChecked.get(position));
         convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (viewHolder.radioButton.isChecked()) {//当cb被选中时
                    ableChecked.put(position,false);
                    viewHolder.radioButton.setChecked(ableChecked.get(position));

                } else {
                    ableChecked.put(position,true);
                    viewHolder.radioButton.setChecked(ableChecked.get(position));
                    Toast.makeText(context,"选中了"+list.get(position).getPathName(),Toast.LENGTH_SHORT).show();
                }
                Log.i("TAG", "onClick: "+ableChecked.get(position));
            }
        });
         return convertView;
    }
    static class ViewHolder{
        private TextView textViewpath,textViewpathname;
        private RadioButton radioButton;
    }
}

如图的代码,想实现点击item就选中radiobutton,但是现在点击不同的item,但radiobutton都是选中最后一个item上的radiobutton,Toast显示的点击位置是正确的,就是radiobutton位置不对,怎么解决啊?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • aben111 2020-07-10 10:26
    已采纳

    建议在bean里面添加控制radiobutton选中状态的字段,依靠radiobutton本身的状态呜会导致复用错乱,是因为列表的复用机制导致的

    点赞 评论
  • dabocaiqq 2020-06-18 10:24
    点赞 评论
  • mysky984 2020-06-19 11:22

    xml里面把所有的radioButton放在标签下,应该就可以了

    点赞 评论

相关推荐 更多相似问题