简体   繁体   中英

ArrayAdapter is changing the value of the CheckBox

I don't know what's happening, I've a list of objects and depending of its state it's checked or not ( CheckBox ). I've tried too many ways, because first of all I wanted to return an ArrayList<myObject> with the state updated, but I don't know why the objects were duplicating... and I ended up creating a TreeSet (don't know if it's the better way but at least the objects now doesn't repeat)... well the thing is that on my Adapter I have this :

final Sessio sessio = getItem(position);
    ALAdapter.add(sessio);
    vh.tvSessioName.setText(sessio.getName());
    vh.cbAssist.setChecked(sessio.isState());
    vh.cbAssist.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            Toast.makeText(mContext, "chaning", Toast.LENGTH_SHORT).show();
            sessio.setState(isChecked);
        }
    });

AlAdapter is private TreeSet<Sessio> ALAdapter;

this is working fine, the problem is at the time I re-open the dialog because I save the TreeSet on a json with Gson as follows :

Gson gson = new Gson();
String json = mPrefs.getString("ArrayListSesio", "");
Type type = new TypeToken <TreeSet<Sessio>> () {}.getType();
ArrayList<Sessio> obj = gson.fromJson(json,type);
return obj == null ? AlSessio : obj;

This is also working fine... I think the problem is on the Adapter because if I uncked some of the CheckBox and I change the state of the Sessio when I re-open the Dialog it shows the Toast like 15 times... and everytime I scroll up/down the state of the CheckBox changes....

What I'm doing wrong? Is there any other way to instead of save it to a TreeSet save it to an ArrayList ?

Problem here is that views are reused, so before using setChecked method you should do this:

vh.cbAssist.setOnCheckedChangeListener(null);
vh.cbAssist.setChecked(sessio.isState());
vh.cbAssist.setOnCheckedChangeListener(/* your listener here */);

Otherwise using setChecked will trigger listener.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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