2012-06-18 100 views
0

我想为我的列表视图做一个上下文菜单,所以当用户长按一行,上下文菜单出现,并且当用户选择一个选项时,行被选中。但是,选择了很多行,它会重复在列表视图中为其他行选择模式。ListView重复选择

同样的情况发生在我点击一行时。 IDK,如果它是视图回收问题,或者是什么。

如何解决这两个问题,因为首先是处理内部onContextItemSelected(MenuItem item)所以我通过操纵MenuItem对象管理行,第二个是在AdapterView.OnItemClickListener处理。

顺便说一句,我使用CursorAdapter来填充ListView。

谢谢。

这里是我的代码:

// Listener for the click on the items in the ListView 
mListViewListener = new AdapterView.OnItemClickListener() 
{ 
    // When the user clicks some item, the Activity that shows the available dates will be shown 
    @Override 
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long arg3) 
    { 
     view.setBackgroundColor(0xff333333); 
    } 
}; 


// Handle the LongClick on the row 
@Override 
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) 
{ 
    super.onCreateContextMenu(menu, view, menuInfo); 
    MenuInflater inflater = getMenuInflater(); 
    inflater.inflate(R.menu.contact_options, menu); 
} 

@Override 
public boolean onContextItemSelected(MenuItem item) 
{ 
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); 
    switch(item.getItemId()) 
    { 
     case R.id.context_menu_item: 
      info.targetView.setBackgroundColor(0xff333333); 

      default: 
      return super.onContextItemSelected(item); 
    } 
} 
+0

你最终的目标是什么:长时间点击改变背景颜色?或者更多? – Sam

+0

@Sam更改我长按的行的背景(在我从LongClick创建的上下文菜单中选择一个选项后),并更改我简单单击的行的背景。 – rogcg

+0

检查你的行重点,看看会发生什么 – SpicyWeenie

回答

1

像这样的事情在你的CursorAdapter应该工作:

private Set<String> mSelectedContactNumbers = new HashSet<String>(); 

@Override 
public void bindView(View view, Context context, final Cursor cursor) 
{ 
    final String contactNumber = cursor.getString(cursor.getColumnIndex("contact_number")); 
    view.setOnClickListener(new View.OnClickListener() 
    { 
     @Override 
     public void onClick(View v) 
     { 
        if (!mSelectedContactNumbers.remove(contactNumber)) { 
         mSelectedContactNumbers.add(contactNumber); 
        } 
        notifyDataSetChanged(); 
     } 
    }); 
    if (mSelectedContactNumbers.contains(contactNumber)) { 
     view.setBackgroundColor(0xff333333); 
    } else { 
     view.setBackgroundColor(0); 
    } 
    createView(view, cursor);  
} 

这仅仅是一个快速的解决方案。您可以在OnItemClickListener中调用的适配器中创建toggleSelected函数。这样它会更好一点。