Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin.Forms center title and transparent navigation bar - Android

I am using Xamarin.Forms and I have a problem getting 2 things to work on Android:

  1. I want to set ActionBar to be transparent, setting BarBackgroundColor works with every color but not with transparent.
  2. I want the page title to be centered, just like it is on iOS.

    MainPage = new NavigationPage(
           new LoginPage(){Title = "Center"}) {BarBackgroundColor = Color.Transparent});
    

Can anyone help me with this?

like image 978
Bonobo Avatar asked Oct 20 '15 06:10

Bonobo


1 Answers

I have recently encounter the same problem, I was using MasterDetailPage in Xamarin.Forms and in android it does not set the title to center.

So, obvious route was to create a custom renderer and override its OnLayout method, and find Toolbar's TextView and set its Gravity to Center, easy right?

But hey when i try to do this myTextView.Gravity = Android.Views.GravityFlags.Center it just doesn't work. I tried setting ForegroundGravity but no effect.

So finally i've calculated center X position and set TextView X position and VOILLA! it is now in center. Here is my solution.

[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);
                }
            }
        }
    }
}
like image 156
Fahadsk Avatar answered Sep 23 '22 20:09

Fahadsk