简体   繁体   中英

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.

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 .

BTW, I'm using CursorAdapter to populate the 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:

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. That way it will be an little nicer.

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