0
似乎我做错了什么,因为每当我打开片段时,所有复选框都会被选中。在SharedPreferences中保存复选框状态
但是当我点击其中一个取消选中时,我再次调用savePreference方法,其中checkBox.isChecked为false。但是在该方法中,该值设置为true。因此,我认为这就是为什么每次运行应用程序时都会检查复选框。
编辑:器isChecked将始终返回我真实的,甚至当我取消
这里是我的代码:
public class FilterAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> mFilters;
private ArrayList<Integer> mPictures;
private Typeface Bebas, DroidSans;
private CheckBox checkBox;
public FilterAdapter(Context context, ArrayList<String> filters, ArrayList<Integer> pictures) {
this.mContext = context;
this.mFilters = filters;
this.mPictures = pictures;
}
@Override
public int getCount() {
return mFilters.size();
}
@Override
public Object getItem(int position) {
return mFilters.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.category_filter_item, null);
}
checkBox = (CheckBox) convertView.findViewById(R.id.check_box);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
savePreferences("CheckBox_Value", checkBox.isChecked());
else {
savePreferences("CheckBox_Value", checkBox.isChecked());
}
}
});
loadSavedPreferences();
DroidSans = Typeface.createFromAsset(mContext.getAssets(), "fonts/DroidSans.ttf");
ImageView filter_img = (ImageView) convertView.findViewById(R.id.category_picture);
TextView filter_category = (TextView) convertView.findViewById(R.id.filter_category);
filter_category.setTypeface(DroidSans);
filter_category.setText(mFilters.get(position));
filter_img.setBackgroundResource(mPictures.get(position));
return convertView;
}
private void savePreferences(String key, boolean value) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(key, value);
editor.apply();
}
private void loadSavedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
boolean checkBoxValue = sharedPreferences.getBoolean("CheckBox_Value", checkBox.isChecked());
if (checkBoxValue) {
checkBox.setChecked(true);
} else {
checkBox.setChecked(false);
}
}
}
http://stackoverflow.com/questions/12621804/saving-state-of-the-checkbox-in-a-custom-list -view-with-checkboxes see this – MOSO
if suggest this coz ur still using the old slow way。使用视图模式。如果(缺陷)没有意义 – MOSO
你的适配器中缺少一些,如果你有多个复选框,那么你为什么采用sharedPrefarance它将覆盖所有的复选框值与最后提供它。因为你在这里拿了一把钥匙。 –