您可以使用自定义渲染器在 android 平台上创建您的自定义 TabbedPage。不同意 Yuri,在 android 上我们可以将图像添加到选项卡,实际上我们可以自定义选项卡的布局。
由于在您的图片中,我看到您没有为每个选项卡使用Icon 属性,因此我将此图标用作关闭按钮。 但是肯定你也不能用这个,它是自己定制的。
在 PCL 中,创建 MyTabbedPage:
public class MyTabbedPage : TabbedPage
{
}
在Android平台上为它创建一个渲染器:
[assembly: ExportRenderer(typeof(MyTabbedPage), typeof(MyTabbedPageRenderer))]
namespace YOURNAMESPACE.Droid
{
public class MyTabbedPageRenderer : TabbedPageRenderer
{
private ObservableCollection<Xamarin.Forms.Element> children;
private IPageController controller;
protected override void SetTabIcon(TabLayout.Tab tab, FileImageSource icon)
{
base.SetTabIcon(tab, icon);
tab.SetCustomView(Resource.Layout.mytablayout);
var imagebtn = tab.CustomView.FindViewById<ImageButton>(Resource.Id.closebtn);
imagebtn.SetBackgroundDrawable(tab.Icon);
var title = tab.CustomView.FindViewById<TextView>(Resource.Id.tabtitle);
title.Text = tab.Text;
imagebtn.Click += (sender, e) =>
{
var closebtn = sender as ImageButton;
var parent = closebtn.Parent as Android.Widget.RelativeLayout;
var closingtitle = parent.FindViewById<TextView>(Resource.Id.tabtitle);
foreach (var child in children)
{
var page = child as ContentPage;
if (page.Title == closingtitle.Text)
{
children.Remove(child);
break;
}
}
};
}
protected override void OnElementChanged(ElementChangedEventArgs<TabbedPage> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
controller = Element as IPageController;
children = controller.InternalChildren;
}
}
}
}
像这样使用它:
<local:MyTabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:TabbedPageForms"
x:Class="TabbedPageForms.MainPage">
<local:TodayPage Title="Today" Icon="hamburger.jpg" />
<local:SchedulePage Title="Schedule" Icon="hamburger.jpg" />
</local:MyTabbedPage>
代码在后面,别忘了把MainPage改成继承自MyTabbedPage:
public partial class MainPage : MyTabbedPage
{
public MainPage()
{
InitializeComponent();
}
}
这里请注意,如果你仔细看我的代码,你会发现我使用每个标签的Title来比较和删除匹配项,它会找到第一个匹配的标题并删除该标题的页面。如果您有多个具有相同标题的选项卡,这可能会导致问题。这是本演示的一个潜在错误,您可以尝试解决它。
更新:
忘记贴mytablayout的代码了,这里是:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="@+id/tabtitle"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_centerInParent="true"
android:gravity="center_horizontal" />
<ImageButton
android:id="@+id/closebtn"
android:layout_height="30dp"
android:layout_width="30dp"
android:scaleType="fitCenter"
android:layout_alignParentRight="true"
android:gravity="center" />
</RelativeLayout>