Xamarin.Forms ListView:设置点击项目的高亮颜色

问题描述:

使用 Xamarin.Forms,如何定义选定/点击的 ListView 项目的突出显示/背景颜色?

Using Xamarin.Forms, how can I define the highlight/background color of a selected/tapped ListView item?

(我的列表有黑色背景和白色文本颜色,所以 iOS 上的默认高亮颜色太亮了.相比之下,在 Android 上根本没有高亮 - 直到一个微妙的水平灰线.)

(My list has a black background and white text color, so the default highlight color on iOS is too bright. In contrast, on Android there is no highlighting at all - up to a subtle horizontal gray line.)

示例:(左:iOS,右:Android;同时按下Barn2")

Example: (left: iOS, right: Android; while pressing "Barn2")

iOS

解决方案:

在自定义ViewCellRenderer 中,您可以设置SelectedBackgroundView.只需使用您选择的背景颜色创建一个新的 UIView 即可.

Within a custom ViewCellRenderer you can set the SelectedBackgroundView. Simply create a new UIView with a background color of your choice and you're set.

public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
{
    var cell =  base.GetCell(item, reusableCell, tv);

    cell.SelectedBackgroundView = new UIView {
        BackgroundColor = UIColor.DarkGray,
    };

    return cell;
}

结果:

注意:

对于 Xamarin.Forms,创建一个 UIView 似乎很重要,而不仅仅是设置当前视图的背景颜色.

With Xamarin.Forms it seems to be important to create a new UIView rather than just setting the background color of the current one.

解决方案:

我在 Android 上找到的解决方案有点复杂:

The solution I found on Android is a bit more complicated:

  1. Resources>drawable 文件夹中创建一个新的drawable ViewCellBackground.xml:

  1. Create a new drawable ViewCellBackground.xml within the Resources>drawable folder:

<?xml version="1.0" encoding="UTF-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" >
        <shape android:shape="rectangle">
            <solid android:color="#333333" />
        </shape>
    </item>
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#000000" />
        </shape>
    </item>
</selector>

它为 UI 元素的默认状态和按下"状态定义了具有不同颜色的实心形状.

It defines solid shapes with different colors for the default state and the "pressed" state of a UI element.

ViewCellView 使用继承的类,例如:

Use a inherited class for the View of your ViewCell, e.g.:

public class TouchableStackLayout: StackLayout
{
}

  • 为此类设置背景资源实现自定义渲染器:

  • Implement a custom renderer for this class setting the background resource:

    public class ElementRenderer: VisualElementRenderer<Xamarin.Forms.View>
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.View> e)
        {
            SetBackgroundResource(Resource.Drawable.ViewCellBackground);
    
            base.OnElementChanged(e);
        }
    }
    

  • 结果: