Xamarin.Forms中心标题和透明导航栏 - Android

Bon*_*obo 7 android android-layout xamarin.android xamarin xamarin.forms

我正在使用Xamarin.Forms,我在Android上运行2件事时遇到了问题:

  1. 我想将ActionBar设置为透明,设置BarBackgroundColor适用于每种颜色但不适用于透明.
  2. 我希望页面标题居中,就像在iOS上一样.

    MainPage = new NavigationPage(
           new LoginPage(){Title = "Center"}) {BarBackgroundColor = Color.Transparent});
    
    Run Code Online (Sandbox Code Playgroud)

谁能帮我这个?

Fah*_*dsk 9

我最近遇到同样的问题,我是用MasterDetailPageXamarin.Forms与Android中并不设置标题中心.

那么,显而易见的路线是创建一个自定义渲染器override及其OnLayout方法,并找到工具栏TextView并将其设置GravityCenter,对吗?

但是,当我尝试这样做时,myTextView.Gravity = Android.Views.GravityFlags.Center它只是不起作用.我试过设置ForegroundGravity但没有效果.

所以最后我计算了中心X的位置并设置了TextViewX位置和VOILLA!它现在在中心.这是我的解决方案.

[assembly: ExportRenderer(typeof(CustomMasterDetailPage), typeof(CustomMasterDetailPageRenderer))]
namespace myApp.Droid
{
    public class CustomMasterDetailPageRenderer : MasterDetailPageRenderer
    {
        protected override void OnLayout(bool changed, int l, int t, int r, int b)
        {
            base.OnLayout(changed, l, t, r, b);

            var toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);

            for (int index = 0; index < toolbar.ChildCount; index++)
            {
                if (toolbar.GetChildAt(index) is TextView)
                {
                    var title = toolbar.GetChildAt(index) as TextView;
                    float toolbarCenter = toolbar.MeasuredWidth / 2;
                    float titleCenter = title.MeasuredWidth / 2;
                    title.SetX(toolbarCenter - titleCenter);
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


VeY*_*roN 2

您需要创建一个自定义渲染器来实现这一点。

[assembly: ExportRenderer (typeof(NavigationPage), typeof(NavigationPageRenderer))]
namespace Droid
{

public class NavigationPageRenderer : NavigationRenderer
{

    protected override void OnElementChanged (ElementChangedEventArgs<NavigationPage> e)
    {
        base.OnElementChanged (e);

        ApplyTransparency ();
    }

    protected override bool DrawChild (Android.Graphics.Canvas canvas, Android.Views.View child, long drawingTime)
    {
        ApplyTransparency ();
        return base.DrawChild (canvas, child, drawingTime);
    }

    void ApplyTransparency ()
    {
        var activity = ((Activity)Context);
        var actionBar = activity.ActionBar;
        actionBar.SetIcon (Resource.Drawable.actionbaricon);
        actionBar.SetBackgroundDrawable (null);
    }
}
}
Run Code Online (Sandbox Code Playgroud)

对我来说,它只能使用 OnElementChanged 和 DrawChild 调用 RemoveAppIconFromActionBar 来工作,否则,当您导航到其他页面时,它会不断添加栏分隔符。

您还需要添加Window.RequestFeature (WindowFeatures.ActionBarOverlay);到 MainActivity 类。

如果有人找到更好的方法来代替使用 DrawChild(),请告诉我。

希望能帮助到你