Android checkBox 在listView 实现单选,并记录保存

时间:2022-04-24 05:15:16

这就是一个逻辑问题,没什么好讲的,但秉着友人的要求还是写写,其实,我挺高兴的,证明我这哥们儿,还是时刻关注着我。我记得他说过,最让我感动的一句话就是:你的博客,就是我的笔记本。

闲话不说了,那我们就来看看,这问题怎么解决?

//将数据与界面进行绑定的操作
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.tvName.setText(personInfos.get(position).getName());
holder.tvTelepHone.setText(personInfos.get(position).getTelephone());
holder.tvAddress.setText(personInfos.get(position).getAddress());

holder.checkBox.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {
SharePreferenceUtil.getInstance().clearDeliveryAddressSp();
holder.checkBox.setChecked(true);
SharePreferenceUtil.getInstance().setDeliveryAddressSp(position);
notifyDataSetChanged();
}
});

//这里判断,用来是RadiaButton只能选着一个
boolean res=false;
if (SharePreferenceUtil.getInstance().getDeliveryAddressSp()==position){
res = true;
}else{
res = false;
//这里可以 返回选择的用户信息
}

holder.checkBox.setChecked(res);

}

思路:说白了,就是用sharepreference 存储checkbox的状态,选中了,就存储为true;

下面是sharepreference 的写法:

/**
* Created by Jim on 2016/11/21.
*/

public class SharePreferenceUtil {

private static class SharePreferenceHolder {
private static final SharePreferenceUtil INSTANCE = new SharePreferenceUtil();
}
private SharePreferenceUtil (){

}
public static final SharePreferenceUtil getInstance() {
return SharePreferenceHolder.INSTANCE;
}

public void setDeliveryAddressSp(int position){
SharedPreferences sharedPreferences = Global.mContext.getSharedPreferences("rb_check_position", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putInt("position", position);
editor.commit();// 提交修改
}

public void clearDeliveryAddressSp(){
SharedPreferences sharedPreferences = Global.mContext.getSharedPreferences("rb_check_position", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.clear();

}

public int getDeliveryAddressSp(){
SharedPreferences sharedPreferences = Global.mContext.getSharedPreferences("rb_check_position", Context.MODE_PRIVATE);
if (sharedPreferences!=null){
return sharedPreferences.getInt("position",-1);
}else {
return -1;
}

}

}

哎,其实,就怎么简单。