2013-06-05 154 views
0

我使用我的应用程序列表视图正由DB(SimpleCursorAdapter)填充多重选择。列表视图选择有一些奇怪的行为。的ListView非选定项得到选择

如果在数据库中超过7个项目,如果我在列表视图中选择第1项,第8项也被选中,即使我没有选择第8项,反之亦然。如果我选择第9项,则第2行被选中。

这里发生了什么?

代码:

String[] projection = { ..table_columns..}; 

String[] from = { table_columns..}; 
Cursor cursor = contentResolver.query(SomeContentProvider.CONTENT_URI, projection, null, null, 
     null); 

// the XML defined views which the data will be bound to 
int[] to = new int[] { 
R.id.color, 
R.id.name, 
R.id.desc, 
}; 


// create the adapter using the cursor pointing to the desired data 
//as well as the layout information 
dataAdapter = new SimpleCursorAdapter(
this, R.layout.layout_main, 
cursor, 
from, 
to, 
0); 

dataAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() { 
@Override 
    public boolean setViewValue(View view, Cursor cursor, int column) { 
     int nNameIndex = cursor.getColumnIndexOrThrow(EventsTable.COLUMN_NAME); 
     if(column == nNameIndex){ 
      TextView nname = (TextView) view; 
      String name = cursor.getString(cursor.getColumnIndex(EventsTable.COLUMN_NAME)); 

      String formatted_name = "NAME: " +name; 

      nname.setText(formatted_name); 
      return true; 
     } 
     return false; 
    } 
}); 

    listView.setAdapter(dataAdapter); 
    listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 
    listView.setOnItemLongClickListener(new OnItemLongClickListener() { 
     @Override 
     public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) { 

      if (!listView.isItemChecked(pos)){ 
       listView.setItemChecked(pos, true); 
       v.setBackground(getResources().getDrawable(R.drawable.listview_bg_selected)); 
       v.setSelected(true); 

      } else { 
       listView.setItemChecked(pos, false); 
       v.setBackground(getResources().getDrawable(R.drawable.listview_bg)); 
       v.setSelected(false); 
      } 

      if (listView.getCheckedItemCount() > 0) { 

       if (mMode == null) { 
        mMode = startActionMode(new ActionModeCallback()); 
       } else { 
        mMode.setTitle(listView.getCheckedItemCount() + " " + "Selected"); 

       } 
      } else { 
       if (mMode != null) { 
        mMode.finish(); 


       } 
      } 

      return true; 
     } 
    }); 

回答

1

我怀疑这是因为在你的适配器的bindView如果该项目被选中你不检查,然后适当地改变背景。

你遇到被回收的意见。

所以,当你滚动,并说项目一个熄灭的观点和选择,对第1项的视图再用于项目8

所以加这样的事情你的观点粘合剂

 int post = cursor.getPosition(); 
     if (!listView.isItemChecked(pos)){ 
       v.setBackground(getResources().getDrawable(R.drawable.listview_bg_selected)); 

     } else { 
       v.setBackground(getResources().getDrawable(R.drawable.listview_bg)); 
     } 
+0

如果检查项目,我该如何检查bindView?请检查我的代码,我已更新它。我没有使用自定义的'SimpleCursorAdapter' – input

+0

添加的代码示例。代码与首先设置背景的方式类似。检查状态,并根据数据设置或取消设置。 取消设置非常重要,因为回收视图可能已将其视图设置为反映选择。 –

+0

谢谢你的工作就像一个魅力。但奇怪的是,我失去了造型。 – input