I have created a ListView with Arraylist as below:

nAdapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_checked,nArrayList);

mListView.setAdapter(nAdapter);

then the setOnItemClickListener():

mListView.setOnItemClickListener(new OnItemClickListener(){

    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
       if(((CheckedTextView) arg1).isChecked()){
            ((CheckedTextView)arg1).setChecked(false);
       }else{
        ((CheckedTextView)arg1).setChecked(true);
       }
}});

The problem is if I select an item, every 7 or 8 item (the first item not in the current view, but viewed when scrolled up) further down on the list also get selected. This happens though out the list.

Can someone explain what is happening here ?

有帮助吗?

解决方案

To solve this, simply use:

mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

and remove your OnItemClickListener.


Android employs View recycling. Imagine a ListView with 1,000 rows: it is wasteful to have a unique View for each row when the user can only see a handful at a time. So the adapter wisely only creates enough unique Views that are visible (about 7 or 8 in your case) and recycles these unique Views to show all 1,000 rows; creating a faster app.

The errant checkmarks that you are seeing in your rows happens when the "previous" row was checked but not cleared after the row is recycled and filled with the "new" data.

Hope that makes sense otherwise please watch Android's Romain Guy discuss this phenomena here.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top