如何在Xamarin中修改TabbedPage选中标签的标题文字颜色
实现方案
你目前的代码固定了所有标签的文字颜色为灰色,只需修改颜色配置逻辑即可实现选中态、未选中态的颜色区分,推荐两种实现方式:
方式一:使用带状态的ColorStateList(最优方案)
无需额外监听事件,直接修改现有SetTabIconImageSource方法中的颜色配置即可,系统会自动根据标签选中状态匹配对应颜色:
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; // 配置状态与对应的颜色 int[][] stateList = new int[][] { new int[] { Android.Resource.Attribute.StateSelected }, // 选中状态 new int[] { } // 默认未选中状态 }; int[] colorList = new int[] { Android.Graphics.Color.Black, // 选中时为黑色 Android.Graphics.Color.Gray // 未选中时为灰色 }; ColorStateList tabTextColor = new ColorStateList(stateList, colorList); title.SetTextColor(tabTextColor); }
注意:请确保你的自定义布局文件
subscriptionsTabLayout.axml中,TextView没有硬编码textColor属性,否则会覆盖代码中设置的状态颜色。
方式二:监听标签选中事件手动切换颜色
如果后续需要扩展更复杂的选中交互逻辑,可以通过监听TabLayout的选中、取消选中事件手动修改颜色:
首先在自定义渲染器的OnElementChanged生命周期中注册事件监听:
protected override void OnElementChanged(ElementChangedEventArgs<TabbedPage> e) { base.OnElementChanged(e); if (e.NewElement != null && ViewPager != null) { var tabLayout = (Google.Android.Material.Tabs.TabLayout)ViewPager.Parent; // 注册标签选中、取消选中事件 tabLayout.TabSelected += OnTabSelected; tabLayout.TabUnselected += OnTabUnselected; } }
实现事件处理方法:
private void OnTabSelected(object sender, Google.Android.Material.Tabs.TabLayout.TabSelectedEventArgs e) { var titleView = e.Tab.CustomView?.FindViewById<TextView>(Resource.Id.tv); if (titleView != null) { titleView.SetTextColor(Android.Graphics.Color.Black); } } private void OnTabUnselected(object sender, Google.Android.Material.Tabs.TabLayout.TabUnselectedEventArgs e) { var titleView = e.Tab.CustomView?.FindViewById<TextView>(Resource.Id.tv); if (titleView != null) { titleView.SetTextColor(Android.Graphics.Color.Gray); } }
内容的提问来源于stack exchange,提问作者Arvind Chourasiya
相关产品推荐
相关产品推荐

