[英]ListView repeating selection
I'm trying to make a context menu for my listview, so when a user long press a row, the context menu shows up, and when the user chooses an option, the row gets selected. 我正在尝试为列表视图创建上下文菜单,因此当用户长按一行时,将显示上下文菜单,并且当用户选择一个选项时,该行将被选中。 However a lot of rows are selected, it repeats the selection in pattern for other rows in the listview.
但是,选择了很多行,它会在模式中对列表视图中的其他行重复选择。
The same happens when I simply click a row. 当我简单地单击一行时,也会发生同样的情况。 IDK if it's a problem with view recycling, or what.
IDK(如果视图回收有问题)。
How to solve both issues, since first is handled inside onContextItemSelected(MenuItem item)
so I manage the row by manipulating the MenuItem
object, and the second is handled in AdapterView.OnItemClickListener
. 如何解决这两个问题,因为第一个是在
onContextItemSelected(MenuItem item)
内部处理的,所以我通过操作MenuItem
对象来管理行,第二个是在AdapterView.OnItemClickListener
处理的。
BTW, I'm using CursorAdapter to populate the ListView. 顺便说一句,我正在使用CursorAdapter填充ListView。
Thanks. 谢谢。
Here is my code: 这是我的代码:
// 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);
}
}
Something like this in your CursorAdapter should work: 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);
}
This is just a quick solution. 这只是一个快速的解决方案。 You create a toggleSelected function in the adapter that you can call from OnItemClickListener.
您可以从OnItemClickListener调用的适配器中创建toggleSelected函数。 That way it will be an little nicer.
这样,它将变得更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.