首页 > 解决方案 > 如何在 Xamarin 中更改选定的选项卡标题颜色

问题描述

我正在研究 xamarin 表格TabbedPage。我必须只将选定的选项卡标题设置为不同的颜色。

这是我的代码

<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
            xmlns:local="clr-namespace:go.Models" 
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
            x:Class="Bite2.ViewsForN.SubsView">
    <!--Tab 1 starts here-->
    <ContentPage Title="Buy Subscriptions">
        <StackLayout>
        </StackLayout>
    </ContentPage>
    
    <!--Tab 2 starts here-->
    <ContentPage Title="My Subscriptions">
        <StackLayout>
        </StackLayout>
        
    </ContentPage>
</TabbedPage>

在 customrender 中,我将选项卡文本颜色设置为灰色。我需要黑色用于选定的选项卡,灰色用于未选定的选项卡。

  protected override void SetTabIconImageSource(Google.Android.Material.Tabs.TabLayout.Tab tab, Drawable icon)
    {
        base.SetTabIconImageSource(tab, icon);
        tab.SetCustomView(Resource.Layout.subscriptionsTabLayout);
        var title = tab.CustomView.FindViewById<TextView>(Resource.Id.tv);
        title.Text = tab.Text;
        ColorStateList csl = ColorStateList.ValueOf(Android.Graphics.Color.Gray);
        title.SetTextColor(csl);
    }

我怎样才能做到这一点?

标签: xamarinxamarin.formstabsrenderer

解决方案


我需要黑色用于选定的选项卡,灰色用于未选定的选项卡。

您不需要使用 CustomRender 来实现这一点。您可以只使用属性UnselectedTabColorSelectedTabColorof TabbedPage

请参考以下代码:

<?xml version="1.0" encoding="UTF-8"?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
            xmlns:local="clr-namespace:TabbedPageWithNavigationPage;assembly=TabbedPageWithNavigationPage" 
            x:Class="TabbedPageWithNavigationPage.MainPage"
            UnselectedTabColor="Gray"
            SelectedTabColor="Black"
            >
    
</TabbedPage>

推荐阅读