I am trying to center the title of the page in Android in Xamarin forms. I have access to the tool bar and was able to set the font family. But I am not able to set the text alignment or gravity to center.
var context = (Android.App.Activity)Forms.Context; var toolbar = context.Resources.GetIdentifier("toolbar", "id", context.PackageName); var view = context.FindViewById(toolbar);
I tried the following:
ForegroundGravity
view.SetForegroundGravity(GravityFlags.Center);
Text Alignment
view.TextAlignment = Android.Views.TextAlignment.Center;
Access the Childs of the toolbar and set the direction and alignment.
if (view is ViewGroup)
{
var g = view as ViewGroup;
for (var i = 0; i < g.ChildCount; i++)
{
SetTypefaceToAllTextViews(g.GetChildAt(i), typeface);
g.GetChildAt(i).TextAlignment = Android.Views.TextAlignment.Center;
g.GetChildAt(i).TextDirection = TextDirection.Rtl;
}
}
The issue is that, I don't have direct access to the gravity of the title.
EDIT #1:
I added this code after casting the view and I can see the font is changing but it won't get centered or any other alignment for some reason
if (view is TextView)
{
var tv = view as TextView;
tv.Typeface = typeface;
tv.TextAlignment = Android.Views.TextAlignment.Center;
tv.Gravity = GravityFlags.CenterHorizontal;
}
EDIT #2: I was able to add the following to the effect based on an answer below and it somehow centered the element but not exactly at the center. Somehow it's to the right side of the center unless if there are 2 icons in the toolbar on the right and the left side, then, the title will be really centered. Tested on Android 8. Also, I found this issue on a similar solution.
https://github.com/CrossGeeks/CustomNavigationBarSample/issues/3
from Android Tool Bar Center using Effects in Xamarin forms
No comments:
Post a Comment