Xamarin Android ListView选择项目并更改行颜色 [英] Xamarin Android ListView select item and change row color

查看:566
本文介绍了Xamarin Android ListView选择项目并更改行颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是xamarin的新手,我一直在到处寻找一种在ListView中选择项目并更改行颜色以使用户知道选择哪行的方法.这就是我得到的

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.

推荐答案

在ListView Adapter GetView方法(或RecyclerView Adapter OnBindViewHolder方法)中,插入如下代码:

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:将列表视图项设置为"selected" (突出显示)

这篇关于Xamarin Android ListView选择项目并更改行颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆