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

用開源框架 PagerSlidingTabStrip 做 Android 頂部導航

編輯:關於 Android 開發

開源框架官網:https://github.com/astuetz/PagerSlidingTabStrip

它可以理解為搭配 ViewPager 使用的「互動式頁面指示器」——頂部一排可滑動、可點擊的標籤,跟著頁面一起動。

先上效果圖:

為了示範 pstsIndicatorHeight 與 pstsUnderlineHeight 的差別,我刻意把兩者設成不同的值以便對照(示範中做了去除 ActionBar 的處理)。相比單獨使用 ViewPager、或 ViewPager 與 Fragment 的簡單嵌套,這次加入 PagerSlidingTabStrip 之後,頁面導航的切換效果明顯更完整。

一、基本屬性

· pstsIndicatorColor    滑動指示條的顏色

· pstsUnderlineColor   底部整條全寬線的顏色

· pstsDividerColor    標籤之間分隔線的顏色

· pstsIndicatorHeight   滑動指示條的高度

· pstsUnderlineHeight   底部全寬線的高度

· pstsDividerPadding   分隔線上下的內距

· pstsTabPaddingLeftRight 每個標籤左右內距

· pstsScrollOffset    選中標籤的捲動偏移

· pstsTabBackground    每個標籤的背景,應為 StateListDrawable

· pstsShouldExpand    設為 true 時,各標籤等寬平均分配整個螢幕,預設 false

· pstsTextAllCaps     設為 true 時標題全部大寫,預設 true

以上屬性都各自對應 getter 與 setter,執行期也能隨時修改。

二、本次示範的程式碼結構

三、去掉 ActionBar

在 res/values/styles.xml 中把主題換成 NoActionBar 版本:

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

完整的 styles.xml:

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
</resources>

四、加入相依

使用 Android Studio 2.2,仍然在 build.gradle 的 dependencies 中直接加上:

compile 'com.astuetz:pagerslidingtabstrip:1.0.1'

五、佈局檔

先把顏色抽成資源,res/values/colors.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="color_theme">#489cfa</color>
    <color name="transparent">#00000000</color>
    <color name="yellow">#fc9630</color>
</resources>

(1)主佈局 activity_main.xml。PagerSlidingTabStrip 與 ViewPager 搭配使用,這裡把 ViewPager 放在 TabStrip 下方(注意別忘了宣告 app 命名空間):

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.mly.panhouye.pagerslidingtabstripdemo.MainActivity">

    <com.astuetz.PagerSlidingTabStrip
        android:id="@+id/pst"
        android:layout_width="match_parent"
        android:layout_height="48dip"
        android:background="@color/color_theme"
        app:pstsShouldExpand="true"
        app:pstsTabBackground="@color/transparent"
        app:pstsIndicatorHeight="5dp"
        app:pstsIndicatorColor="@color/yellow"
        app:pstsTextAllCaps="false"
        app:pstsUnderlineHeight="15dp" />

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/pst"/>
</RelativeLayout>

這裡 pstsIndicatorHeight 設 5dp、pstsUnderlineHeight 設 15dp,就是為了讓「指示條」與「底部線」兩者高度不同、便於分辨。

(2)Fragment 的佈局。本次只示範簡單效果,fragment_pan、fragment_hou、fragment_ye 三個檔只有文字不同,以下以 fragment_pan.xml 為例:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="潘"
        android:textSize="100sp" />
</LinearLayout>

(3)每個 Fragment 佈局對應一個 Fragment 類別,以 fragment_pan.xml 為例:

public class PanFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_pan, null);
        return view;
    }
}

六、Java 實作

public class MainActivity extends AppCompatActivity {
    PagerSlidingTabStrip pst;
    ViewPager viewPager;
    ArrayList<Fragment> fragments;
    // pst 的標題
    String[] titles = {"潘", "侯", "爺"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pst = (PagerSlidingTabStrip) findViewById(R.id.pst);
        viewPager = (ViewPager) findViewById(R.id.pager);

        fragments = new ArrayList<>();
        // 加入集合時注意順序,需與 titles 對齊
        fragments.add(new PanFragment());
        fragments.add(new HouFragment());
        fragments.add(new YeFragment());

        FragmentManager fragmentManager = getSupportFragmentManager();
        viewPager.setAdapter(new MyPagerAdapter(fragmentManager, titles, fragments));
        viewPager.setCurrentItem(0);

        /**
         * 當 ViewPager 的 OnPageChangeListener 回呼時,PagerSlidingTabStrip 會一起變動。
         * 這部分都已封裝在 setViewPager() 裡,直接呼叫即可。
         */
        pst.setViewPager(viewPager);
        pst.setTextSize(30);
    }

    /** 自定義適配器 */
    class MyPagerAdapter extends FragmentPagerAdapter {
        private String[] titles;
        ArrayList<Fragment> fragments;

        public MyPagerAdapter(FragmentManager fm, String[] titles, ArrayList<Fragment> fragments) {
            super(fm);
            this.titles = titles;
            this.fragments = fragments;
        }

        @Override
        public CharSequence getPageTitle(int position) { return titles[position]; }

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

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

最關鍵的一行是 pst.setViewPager(viewPager):呼叫之後,標籤的點擊、滑動同步與指示條位移都由框架內部接手,我們只要專注在 Fragment 與 Adapter 就好。

以上是 PagerSlidingTabStrip 最基礎的用法。剩下的就交給各位去調那些屬性,試著做出更華麗的切換效果吧。

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