【发布时间】:2017-06-22 16:20:53
【问题描述】:
我想问一下如何在 Xamarin 中为 android 应用程序的选项卡式页面更改选项卡的形状。我知道这显然需要一个自定义渲染器,但是我从哪个类继承?我是继承自 TabbedPageRenderer 还是 TabbedRenderer?另外,我怎么知道哪个函数调用了 Tabs 的渲染,以便我可以覆盖它?
【问题讨论】:
我想问一下如何在 Xamarin 中为 android 应用程序的选项卡式页面更改选项卡的形状。我知道这显然需要一个自定义渲染器,但是我从哪个类继承?我是继承自 TabbedPageRenderer 还是 TabbedRenderer?另外,我怎么知道哪个函数调用了 Tabs 的渲染,以便我可以覆盖它?
【问题讨论】:
我知道这显然需要一个自定义渲染器,但是我从哪个类继承?我是继承自 TabbedPageRenderer 还是 TabbedRenderer?
如果你想改变标签的形状,那么你需要从TabbedPageRenderer 初始化你的自定义渲染器。因为只有TabbedPageRenderer 有SetTabIcon 可以覆盖,这样你就可以访问当前的标签对象。
另外,我如何知道哪个函数调用了 Tabs 的渲染以便我可以覆盖它?
您需要重写的是SetTabIcon 方法。通过这种方法,您可以设置当前标签页的自定义视图。
注意:为了让SetTabIcon被调用,你需要设置每个子页面的Icon,否则SetTabIcon不会被调用。
因此,您可以按照以下步骤更改标签的形状:
在 PCL 中创建自定义 TabbedPage:
public class MyTabbedPage:TabbedPage
{
}
在您的页面中使用它:
<local:MyTabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:CustomTabbedPageDemo"
x:Class="CustomTabbedPageDemo.MainPage">
<!--Icon needs to be set in order to call SetTabIcon-->
<local:Page1 Title="Page One" Icon="icon.png"/>
<local:Page2 Title="Page Two" Icon="icon.png"/>
</local:MyTabbedPage>
在Resource/layout中创建.axml视图文件:
<?xml version="1.0" encoding="utf-8"?>
<View xmlns:android="http://schemas.android.com/apk/res/android"
android:background="@drawable/myshape"
android:layout_width="match_parent"
android:layout_height="match_parent"></View>
在Resource/drawable中定义一个自定义形状xml文件(MyShape.xml),你可以定义任何你想要的形状:
<?xml version="1.0" encoding="utf-8" ?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF"
android:angle="270"/>
</shape>
为您的自定义标签页创建自定义渲染器,并覆盖SetTabIcon:
[assembly:ExportRenderer(typeof(MyTabbedPage),
typeof(MyTabbedPageRenderer))]
namespace CustomTabbedPageDemo.Droid
{
public class MyTabbedPageRenderer:TabbedPageRenderer
{
protected override void SetTabIcon(TabLayout.Tab tab, FileImageSource icon)
{
base.SetTabIcon(tab, icon);
tab.SetCustomView(Resource.Layout.tab_view);
}
}
}
(可选)您可以通过删除android:background 的Resource/Tabbar.axml 的TabLayout 来删除标签栏的背景图片:
<android.support.design.widget.TabLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:tabIndicatorColor="@android:color/white"
app:tabGravity="fill"
app:tabMode="fixed" />
这里是完整的demo,可以参考:CustomTabbedPageDemo。
【讨论】:
tab.SetCustomView(Resource.Layout.tab_view);。您可以使用tab_view 中的任何视图。
Something similar to puzzle pieces fitted together and I would also like to have text titles shown on them.,无法使用android view来实现,甚至在原生android应用程序中也无法实现,您可以参考this thread进行解释。