我尝试使用一个图标,而不是我的Xamarin.Forms应用程序主页上的标题。
我读过很多相关的话题,但我没有找到任何解决方案:
在iOS上,通过在我的第一页中添加以下内容可以很容易地完成这一任务:
NavigationPage.SetTitleIcon(this, "navbar_logo.png");
在Android上,我在上添加了这个
<ImageView android:src="@drawable/navbar_adp_logo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
这是可行的,但是这个图标现在在Android上的每个页面上都可以看到.
当我导航到另一个页面时,我尝试使用呈现器来隐藏图标。为此,我想使用覆盖OnViewAdded()方法:
public class CustomNavigationPageRenderer : NavigationPageRenderer
{
public override void OnViewAdded(Android.Views.View child)
{ ... }
}
我尝试使用OnViewAdded(),因为我在QuickWatch中看到,每次在Xamarin.Forms应用程序中导航时,都会调用该方法。
我还注意到,该方法在导航过程中被调用了2次:
因此,我试图将子对象转换为Xamarin.Forms.Platform.Android.PageContainer,,但是我做不到,因为这个对象是“内部的”:
PageContainer由于其保护方法而无法访问。
--如果我能用QuickWatch来做的话,为什么我不能用代码来做呢?我看不出还有什么办法能实现这一点..。你有什么建议吗?
发布于 2017-08-28 11:49:05
您应该重写OnElementChanged
方法并查找对CurrentPage
属性的更改。这样,您将始终知道何时显示特定的页面,并可以隐藏或显示工具栏图标。
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName.Equals("CurrentPage"))
// If we're on MainPage show the icon, otherwise hide it
ChangeToolbarIconVisibility(Element.CurrentPage is MainPage);
}
private void ChangeToolbarIconVisibility(bool visible)
{
var toolbarIcon = FindViewById<ImageView>(Resource.Id.toolbarIcon);
toolbarIcon.Visibility = visible ? Android.Views.ViewStates.Visible : Android.Views.ViewStates.Gone;
}
要完成此工作,请记住将id添加到修改后的工具栏布局中:
<ImageView android:src="@drawable/navbar_adp_logo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="@+id/toolbarIcon" />
发布于 2017-08-28 12:44:03
您可以通过使用消息中心来完成任务,并定义您想要做的事情。假设您希望在MainPage上设置一个图标,而其他要删除it.You的则可以使用以下内容:
在非主页上:
MessagingCenter.Send<Page, string>(this, "toolbar", "notmain");
在主页上:
MessagingCenter.Send<Page, string>(this, "toolbar", "main");
您在MainActivity中订阅这些消息,如下所示。
var toolbarIcon = FindViewById<ImageView>(Resource.Id.navbar_adp_logo);
//recommendation: do not use lambda, define a delegate function
MessagingCenter.Subscribe<Page, string>(this, "toolbar", (page, toolbar) =>
{
if (toolbar == "main")
{
toolbarIcon.Visibility = ViewStates.Visible;
}
else
{
toolbarIcon.Visibility = ViewStates.Gone;
}
});
不要忘记在xaml中定义
android:id="@+id/navbar_adp_logo"
如果您只想在一个页面上发送消息,那么您可以在所需的页面上执行一次以下操作,而不是从每个页面发送消息。
protected override void OnDisappearing()
{
base.OnDisappearing();
MessagingCenter.Send<Page, string>(this, "toolbar", "notmain");
}
protected override void OnAppearing()
{
base.OnAppearing();
MessagingCenter.Send<Page, string>(this, "toolbar", "main");
}
https://stackoverflow.com/questions/45922373
复制