目前正在开发一个我想使用AppCompat的项目,并且在大多数页面上都要求设置标题和副标题.
它根本不能使用AppCompat – 既不设置属性也不使用自定义视图.
不使用AppCompat时,两者都按预期工作.完整的源代码可用here所以如果你好奇的话就运行应用程序:)
using System.ComponentModel; using Android.App; using Android.Widget; using App1.Droid.Renderers; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; #if __APPCOMPAT__ using NavigationRenderer = Xamarin.Forms.Platform.Android.AppCompat.NavigationPageRenderer; #else using NavigationRenderer = Xamarin.Forms.Platform.Android.NavigationRenderer; #endif [assembly: ExportRenderer(typeof(NavigationPage),typeof(NavigationPageRenderer))] namespace App1.Droid.Renderers { public class NavigationPageRenderer : NavigationRenderer { protected override void OnElementChanged(ElementChangedEventArgs<NavigationPage> e) { base.OnElementChanged(e); SetCustomView(e.NewElement.CurrentPage.GetType().Name); } private void SetCustomView(string view) { var activity = (Activity)Context; #if __APPCOMPAT__ var actionBar = ((FormsAppCompatActivity)Context).SupportActionBar; #else var actionBar = activity.ActionBar; #endif actionBar.Title = view; actionBar.Subtitle = " -> " + view; var abv = new LinearLayout(activity) { Orientation = Orientation.Vertical }; var main = new TextView(activity) { Text = view,}; main.SetTextColor(Color.Aqua.ToAndroid()); main.SetPadding(4,4,2,6); abv.AddView(main); abv.AddView(new TextView(activity) { Text = " -> " + view }); actionBar.SetDisplayShowCustomEnabled(true); actionBar.CustomView = abv; } protected override void OnElementPropertyChanged(object sender,PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender,e); if (e.PropertyName.Equals("CurrentPage")) { SetCustomView(((NavigationPage)sender).CurrentPage.GetType().Name); } } } }
解决方法
所以它看起来像NavigationPage
uses its own Toolbar instance.这就是为什么在SupportActionBar上设置属性没有做任何事情.
我能够通过覆盖OnViewAdded()来获得它的工作,以便在添加时获得对新工具栏的引用:
public override void OnViewAdded(Android.Views.View child) { base.OnViewAdded(child); if (child.GetType() == typeof(Support.Toolbar)) toolbar = (Support.Toolbar)child; }
然后使用SetCustomView()内部的引用来设置Subtitle,因为Title已经自动设置.
Here’s the complete renderer class 原文链接:https://www.f2er.com/android/309846.html