samedi 2 mai 2015

Android: how to remove checked rows in ListView?

When I click a button I make this listener find which items are checked in order to delete them

            SparseBooleanArray checkedItemPositions = list.getCheckedItemPositions();
            int itemCount = list.getChildCount();
            for(int i=0; i<itemCount; i++){
                    if(checkedItemPositions.get(i))
                        Log.v("DELETE TEST - position ", Integer.toString(i)+ " item checked");
                    else
                        Log.v("DELETE TEST - position ", Integer.toString(i)+ " item not checked");
                }
                checkedItemPositions.clear();

This is the list used in the preceding listener

  <ListView
    android:id="@+id/list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:choiceMode="multipleChoice">
  </ListView>

This is the layout used by the custom adapter with layout inflater

<LinearLayout xmlns:android="http://ift.tt/nIICcg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center">

   <CheckedTextView
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="name"
       android:id="@+id/name"
       android:checkMark="?android:attr/listChoiceIndicatorMultiple"
       android:gravity="left|center_vertical" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="field1"
            android:layout_weight="1"
            android:layout_gravity="center"
            android:gravity="right"/>
        <TextView
            android:id="@+id/number"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="number"
            android:layout_weight="2"
            android:layout_gravity="center"/>
    </LinearLayout>

It seems that Android load only a fixed number of cells. If the screen space can show only N cells then childCount will return this number even if there are more of N cells in the real list. So when I see if they are checked I get only N results, even if I scrolled the entired list and checked some other "not-showed" cell.

Example:

  • cell 0
  • cell 1 checked
  • cell 2
  • cell 3
  • cell 4 checked

If N=3 and the screen shows 3 cells from 0 to 2 I get a list of false, true, false from 0 to 2 and I miss false,true from 3-4.

There must be some mistake. I'd like to do a multiplice choice deletion in listviews but this behaviour is odd. Please tell me if there is also a better way.




Aucun commentaire:

Enregistrer un commentaire