简体   繁体   中英

How to keep checkbox selection on listview items after adding and sorting?

This is a ListView using a multiple choice adapter.

public class ExampleActivity extends ListActivity {

    private ListView list;
    private List<String> items;
    private ArrayAdapter<String> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_example);
        this.list = this.getListView();
        this.items = new ArrayList<String>();
        this.items.add("A");
        this.items.add("C");
        this.items.add("D");
        this.items.add("D");
        this.adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, items);
        this.list.setAdapter(adapter);

        this.user(); // simulating user selecting C

        this.button(); // simulating user press some button who adds items to list
    }

    private void user() {
        this.list.setItemChecked(1, true);
    }

    private void button() {
        this.items.add("B");
        Collections.sort(this.items);
        this.adapter.notifyDataSetChanged();
    }
}

If user selects C (index 1), and if then user press button to add items to list and sort (like B), B (new index 1) is going to be selected instead of C. How can this issue be solved?

This is because you make selection for index 1

 this.list.setItemChecked(1, true); // selects C

and after make the insertion and sort , B is the item with index 1

try this

this.list.setItemChecked(this.list.indexOf("c"),true);

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