I am using Xamarin.Forms and I have a problem getting 2 things to work on Android:
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?
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);
}
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With