Xamarin.Forms ListView:设置点击项目的高亮颜色 [英] Xamarin.Forms ListView: Set the highlight color of a tapped item

查看:26
本文介绍了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);
        }
    }
    

  • 结果:

    这篇关于Xamarin.Forms ListView:设置点击项目的高亮颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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