问题
I am adding custom view in Center of ToolbarItem from NavigationPageRenderer for android. But it doesn't seems to be working. See my code below
public class CustomNavigationPageRenderer : NavigationPageRenderer
{
public override void OnViewAdded(Android.Views.View child)
{
base.OnViewAdded(child);
var lastPageElement?.Navigation?.NavigationStack?.Last().ToString();
if (lastPage == "ParentDashboardPage")
{
LayoutInflater li = LayoutInflater.From(Context);
Android.Views.View customView = li.Inflate(Resource.Layout.customActionbar, null);
var _toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
_toolbar.RemoveAllViews();
//_toolbar.AddView(text,new Toolbar.LayoutParams(GravityFlags.Center)); Even this not working
_toolbar.AddView(customView);
}
}
}
customActionbar.axml file below:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:text=" Dashboard"
android:textColor="@color/white"
android:layout_gravity="center"
android:id="@+id/tvActionBarTitle"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_centerVertical="true"
android:layout_centerInParent="true"
android:textSize="17dp" />
<ImageView
android:layout_gravity="right"
android:layout_width="30dp"
android:layout_height="wrap_content"
android:id="@+id/item2"
android:src="@drawable/bell"
android:layout_alignParentRight="true" />
</RelativeLayout>
Output screensshot below:
回答1:
If you are using a Xamarin.Forms app based on Shell then you can easily achieve this using Shell.TitleView without the need of a custom renderer, define your title content, bind it or even style it as you like.
Inside your ContentPage
:
<Shell.TitleView>
<StackLayout Orientation="Horizontal" Spacing="0">
<Label Text="Dashboard"
Opacity="1"
FontAttributes="Bold"
FontSize="20"
TextColor="White"
HorizontalOptions="CenterAndExpand"
HorizontalTextAlignment="Center"
VerticalTextAlignment="Center"/>
<ImageButton Source="Bell.png"
VerticalOptions="CenterAndExpand"
HorizontalOptions="End"
BackgroundColor="transparent"/>
</StackLayout>
</Shell.TitleView>
Also if you need to apply some special adjustments platform-dependent you can use OnPlatform.
Why I choosed those attributes of the style?
To be as close as possible to native default text title. Related question:
Defining Shell.TitleView while preserving the title text of tabs in shell, but seems showing in a different font
来源:https://stackoverflow.com/questions/49913799/how-to-add-custom-view-in-center-of-toolbaritem-from-renderer