mardi 6 décembre 2016

Listview checkbox becomes unselected when scroll down

I have created a custom listview with a checkbox and two line of text. I want to change the checkbox state when I click on the list item (this means that if I click any part of the list item checkbox or text, checkbox will change state). To achieve this I have added this in the custom_list_row xml file:

<RelativeLayout 
xmlns:android="http://ift.tt/nIICcg"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants" >

<CheckBox
    android:id="@+id/checkbox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:focusable="false"
    android:clickable="false" />

and in the java class I did these:

    listview.setAdapter(adapter);

    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            final CheckBox checkBox;
            checkBox = (CheckBox)view.findViewById(R.id.checkbox);


            if(checkBox.isChecked()){
                checkBox.setChecked(false);
            }
            else {
                checkBox.setChecked(true);
            }
        }
    });

This works fine. But the only problem is that when I select some items and scroll down-->the go back to the selected items-->the selected items becomes unselected.

I did not do anything with setOnCheckedChangeListener

What went wrong? Any suggestion to solve this problem will be helpful.

Thanks

Aucun commentaire:

Enregistrer un commentaire