在Android Xamarin中更改选项卡的形状

时间:2017-06-21 02:35:06

标签: android xamarin

我想问一下如何在Xamarin中更改选项卡的形状以获取Android应用程序的标签页。我知道这显然需要一个自定义渲染器,但是我继承哪个类?我是继承TabbedPageRenderer还是TabbedRenderer?另外,我如何知道哪个函数调用Tabs的呈现以便我可以覆盖它?

1 个答案:

答案 0 :(得分:1)

  

我知道这显然需要一个自定义渲染器,但是我继承哪个类?我是继承TabbedPageRenderer还是TabbedRenderer?

如果要更改标签的形状,则需要从TabbedPageRenderer中删除自定义渲染器。因为只有TabbedPageRenderer才能覆盖SetTabIcon,因此您可以访问当前的标签对象。

  

另外,我如何知道哪个函数调用Tabs的呈现以便我可以覆盖它?

您需要覆盖的是SetTabIcon方法。在此方法中,您可以设置当前选项卡的自定义视图。

注意:为了让SetTabIcon被调用,您需要设置每个子页面的Icon,否则SetTabIcon将无法获取调用。

因此,您可以按照以下步骤更改标签的形状:

  1. 在PCL中创建自定义TabbedPage

    public class MyTabbedPage:TabbedPage
    {
    }
    
  2. 在您的页面中使用它:

    <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>
    
  3. .axml中创建Resource/layout视图文件:

    <?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>
    
  4. MyShape.xml中定义自定义形状xml文件(Resource/drawable),您可以定义所需的任何形状:

    <?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>
    
  5. 为自定义标签页创建自定义渲染器,并覆盖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);
            }
        }
    }
    
  6. 您可以选择移除android:background的{​​{1}}的TabLayout来删除标签栏的背景图片:

    Resource/Tabbar.axml
  7. 以下是完整演示,您可以参考:CustomTabbedPageDemo