0

I have a ListView with Checkbox inside a Fragment that extends FragmentList. The strange behavior is multiple items get checked when one item is clicked. Strangely, when the list is scrolled, some item gets automatically selected or deselected and I have no ScrollListener set.

Here's the code :

@Override
public void onStart() {
    super.onStart();
    getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            CheckBox mCheckBox = (CheckBox) view.findViewById(R.id.chk);
            if (mCheckBox.isChecked()) {
                mCheckBox.setChecked(false);
                getListView().setItemChecked(i, false);
            } else {
                mCheckBox.setChecked(true);
                getListView().setItemChecked(i, true);
            }
            mCallback.onArticleSelected(i, isChoice);
        }
    });
}

Required: image
(source: windrealm.org)

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
AlphaQ
  • 656
  • 8
  • 18
  • Listview's views are recycled. If listview recycle a view with checked state, new view will be in checked state. So, you need to save your checked status as list and update view whenever you create. Mostly, we use SparseBooleanArray. – Hein Htet Aung Dec 27 '16 at 10:33

1 Answers1

0

ListView's items recycle while you are scrolling. You should put a boolean parameter (isChecked) to your ListView row object then in your getView method u should initialize your CheckBox with that boolean parameter. For example:

Assume that your row object:

public class Trial{

    public String title;

    public boolean isChecked;

}

In your ListView adapter's getView method, you should check isChecked parameter of your object:

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    LayoutInflater inflater = ((Activity) context).getLayoutInflater();
    View view = inflater.inflate(R.layout.your_listview_item, parent, false);

    Trial item = items.get(position);

    yourHolder.checkBox = (CheckBox) view.findViewById(R.id.chk);
    yourHolder.checkBox.setChecked(item.isChecked);

    return view;
}

Good luck.

Batuhan Coşkun
  • 2,961
  • 2
  • 31
  • 48
  • I'm not implementing any holder or any row object since I'm extending `ListFragment`. The `OnClick` is set inside the `OnStart` method like it is shown in the post (edited). – AlphaQ Dec 27 '16 at 11:03
  • And so what are you showing in the listview? You have not any object list? – Batuhan Coşkun Dec 27 '16 at 11:04
  • It's a simple list with a TextView and a CheckBox. See the updated answer. – AlphaQ Dec 27 '16 at 11:34