Xamarin Android ListView选择项目并更改行颜色

时间:2017-05-30 22:32:52

标签: c# listview xamarin xamarin.android

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

    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);
        }
    }

此方法是项目的点击处理程序

 _cicoListView.ItemClick += FormsListViewOnItemClick;

我唯一的问题是,当我向下滚动其他项目时,因为(这是我最好的猜测)列表视图会回收行和位置。在此先感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

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

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);
}

您也可以使用自定义drawable作为背景,例如:

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