Andoni Zubizarreta
Andoni Zubizarreta

Reputation: 1335

Xamarin Android ListView select item and change row color

I'm new to xamarin and I've been looking everywhere for a way to select an item in a ListView and change the color of the row to let the user know which row is selected. Here is what I got

    private void FormsListViewOnItemClick(object sender, AdapterView.ItemClickEventArgs itemClickEventArgs)
    {
        _cicoListView.SetItemChecked(itemClickEventArgs.Position, true);
        for (var i = 0; i < _ciCos.Count; i++)
        {
            if (itemClickEventArgs.Position == i)
            {
                _selectedId = ((CicoModel)_cicoListView.Adapter.GetItem(i)).Pk;
                //_formsListView.SetItemChecked(itemClickEventArgs.Position, true);   
            }
            _cicoListView.GetChildAt(i)?.SetBackgroundColor(itemClickEventArgs.Position == i ? Color.LightGray : Color.Transparent);
        }
    }

This method is the click handler of the item

 _cicoListView.ItemClick += FormsListViewOnItemClick;

The only problem I have is when I scroll down other items are selected too because (it's my best guess) the list view recycles the rows and the positions. Thanks in advance for the help.

Upvotes: 1

Views: 2652

Answers (1)

Alexandre
Alexandre

Reputation: 589

In your ListView Adapter GetView method (or in your RecyclerView Adapter OnBindViewHolder method), insert the code as follows:

public override View GetView(int position, View convertView, ViewGroup parent)
{
    //inflate or restore convertView
    if(this.myItems[position].selected == true)
    {
        convertView.SetBackgroundColor(Color.Green);
    }
    convertView.Click -= ChangeBackgroundColor;
    convertView.Click += ChangeBackgroundColor;
    // This is to avoid adding more than one EventHandler every time the View is shown in the ListView.
}

private void ChangeBackgroundColor(object sender, EventArgs e)
{
    int position = this.recyclerView.GetChildAdapterPosition((View)sender);
    this.myItems[position].selected = true;
    ((View)sender).SetBackgroundColor(Color.Green);
}

You can also do that by using a custom drawable for background, like in this question:

Android: set list view item as "selected" (highlighted)

Upvotes: 2

Related Questions