Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

客製 SlidingTabLayout 的指示條與分隔線顏色

編輯:關於 Android 開發

客製 SlidingTabLayout 的指示條與分隔線顏色

本文整理自 zhangphil 的分享:https://blog.csdn.net/zhangphil/article/details/48863347

Android SlidingTabLayout 預設的滑動指示條是系統藍色系,分隔線則是灰色。要自訂這兩處顏色,主要靠 setCustomTabColorizer() 這個方法。

整體結構分兩層:MainActivity 只作為容器,負責把 TabFragment 掛上去;真正的 Tab 邏輯都在 TabFragment 裡。使用時別忘了引入 Android 官方提供的 SlidingTabLayout 與 SlidingTabStrip 兩個類別。

程式碼的層次結構如下:

MainActivity.java

package com.zzw.testsetcustomtabcolorizer;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;

public class MainActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            FragmentTransaction transaction = getSupportFragmentManager()
                    .beginTransaction();
            TabFragment fragment = new TabFragment();
            transaction.replace(R.id.content_fragment, fragment);
            transaction.commit();
        }
    }
}

對應的 activity_main.xml 只放一個 FrameLayout 當容器:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.zzw.testsetcustomtabcolorizer.MainActivity">

    <FrameLayout
        android:id="@+id/content_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

TabFragment.java

這裡的設計是為每個分頁建立一個 PagerItem,各自帶著自己的標題、指示條顏色與分隔線顏色,再由 TabColorizer 依位置回傳對應值。

package com.zzw.testsetcustomtabcolorizer;

import java.util.ArrayList;

import com.zzw.testsetcustomtabcolorizer.SlidingTabLayout.TabColorizer;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class TabFragment extends Fragment {

    /** 每個分頁的資料:標題 + 指示條顏色 + 分隔線顏色 */
    private static class PagerItem {

        private final CharSequence mTitle;
        private final int mIndicatorColor;
        private final int mDividerColor;

        public PagerItem(CharSequence mTitle, int mIndicatorColor, int mDividerColor) {
            this.mTitle = mTitle;
            this.mIndicatorColor = mIndicatorColor;
            this.mDividerColor = mDividerColor;
        }

        public Fragment createFragment() {
            return ContentFragment.newInstance(mTitle, mIndicatorColor, mDividerColor);
        }

        public CharSequence getTitle() { return mTitle; }
        public int getIndicatorColor() { return mIndicatorColor; }
        public int getDividerColor() { return mDividerColor; }
    }

    private ArrayList<PagerItem> mTabCards = new ArrayList<PagerItem>();

    /** 每頁的內容,這裡只顯示文字說明 */
    public static class ContentFragment extends Fragment {

        private static final String KEY_TITLE = "title";
        private static final String KEY_INDICATOR_COLOR = "indicator_color";
        private static final String KEY_DIVIDER_COLOR = "divider_color";

        public static ContentFragment newInstance(CharSequence title,
                                                  int indicatorColor,
                                                  int dividerColor) {
            Bundle bundle = new Bundle();
            bundle.putCharSequence(KEY_TITLE, title);
            bundle.putInt(KEY_INDICATOR_COLOR, indicatorColor);
            bundle.putInt(KEY_DIVIDER_COLOR, dividerColor);

            ContentFragment fragment = new ContentFragment();
            fragment.setArguments(bundle);
            return fragment;
        }

        @Override
        @Nullable
        public View onCreateView(LayoutInflater inflater,
                                 @Nullable ViewGroup container,
                                 @Nullable Bundle savedInstanceState) {
            TextView tv = new TextView(getActivity());
            tv.setGravity(Gravity.CENTER);
            return tv;
        }

        @Override
        public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
            TextView tv = (TextView) view;
            Bundle args = getArguments();

            String content = "";
            if (args != null) {
                String title = args.getCharSequence(KEY_TITLE) + "";
                int indicatorColor = args.getInt(KEY_INDICATOR_COLOR);
                int dividerColor = args.getInt(KEY_DIVIDER_COLOR);

                content += "標題:" + title + "\n";
                content += "indicatorColor:"
                        + Integer.toHexString(indicatorColor) + "\n";
                content += "dividerColor:" + Integer.toHexString(dividerColor);
            }
            tv.setText(content);
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 為每個分頁指定指示條與分隔線顏色
        mTabCards.add(new PagerItem("Tab A", Color.RED, Color.RED));
        mTabCards.add(new PagerItem("Tab B", Color.YELLOW, Color.YELLOW));
        mTabCards.add(new PagerItem("Tab C", Color.GREEN, Color.GREEN));
        mTabCards.add(new PagerItem("Tab D", Color.BLUE, Color.BLUE));
        mTabCards.add(new PagerItem("Tab E", Color.CYAN, Color.CYAN));
        mTabCards.add(new PagerItem("Tab F", Color.MAGENTA, Color.MAGENTA));
    }

    @Override
    @Nullable
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment, null);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        ViewPager mViewPager = (ViewPager) view.findViewById(R.id.viewpager);
        mViewPager.setAdapter(new MyFragmentPagerAdapter(getChildFragmentManager()));

        SlidingTabLayout mSlidingTabLayout =
                (SlidingTabLayout) view.findViewById(R.id.sliding_tabs);
        mSlidingTabLayout.setViewPager(mViewPager);

        // 客製顏色的關鍵:TabColorizer 依位置回傳指示條與分隔線顏色
        mSlidingTabLayout.setCustomTabColorizer(new TabColorizer() {

            @Override
            public int getIndicatorColor(int position) {
                return mTabCards.get(position).getIndicatorColor();
            }

            @Override
            public int getDividerColor(int position) {
                return mTabCards.get(position).getDividerColor();
            }
        });
    }

    public class MyFragmentPagerAdapter extends FragmentPagerAdapter {

        public MyFragmentPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return mTabCards.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTabCards.get(position).getTitle();
        }

        @Override
        public Fragment getItem(int position) {
            return mTabCards.get(position).createFragment();
        }
    }
}

fragment.xml 的結構與一般 ViewPager 相同,上方放 SlidingTabLayout,下方放 ViewPager:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.zzw.testsetcustomtabcolorizer.SlidingTabLayout
        android:id="@+id/sliding_tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

整套客製化的核心其實只有一句:TabColorizer 的兩個方法回傳什麼顏色,滑動指示條與分隔線就長什麼樣子。因為它是依 position 回傳,所以能做到每個分頁各自不同色;若希望全體統一,只要讓兩個方法回傳同一個色值即可。此外 SlidingTabLayout 也提供 setSelectedIndicatorColors(...) 這類便捷方法,在不需要逐頁相異的場景下更省事。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved