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

用 TabLayout + ViewPager 實作頂部導航:點擊與左右滑動都能切頁

編輯:Android 開發教學

打開任何一款新聞或資訊類 App,頂部幾乎都會有一排橫向的類別標籤——推薦、熱點、科技、體育、健康。這排標籤的本質,是一組與下方分頁一一對應的入口:點一下標籤換頁,手指左右滑動換頁,標籤又會跟著高亮移動。

早期做這種效果,通常得靠 ViewPagerIndicator 搭配 Fragment 與 ViewPager 三者協力,不僅依賴多,自訂樣式也頗費手腳。隨著 Design Support Library 的成熟,TabLayout 幾乎把這些瑣事都包辦了,本篇就用 TabLayout + Fragment + ViewPager 這套組合,做出一個可點擊、可滑動的頂部導航。

範例同時用到 TabLayout、ViewPager、RecyclerView、CardView 等幾個常見控件。

效果預覽

一、加入依賴

compile 'com.android.support:design:23.2.1'
compile 'com.android.support:recyclerview-v7:23.1.1'
compile 'com.android.support:cardview-v7:23.2.1'

二、主介面布局

布局很單純:一個 TabLayout 加上一個 ViewPager,垂直排列即可。

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

    <android.support.design.widget.TabLayout
        android:id="@+id/tablayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#E0E0E0"
        app:tabIndicatorColor="@color/ind_red"
        app:tabMode="fixed"
        app:tabSelectedTextColor="@color/material_orange"
        app:tabTextColor="@android:color/black"
        app:tabIndicatorHeight="5dp"
        app:tabTextAppearance="@style/TabStyle" />

    <android.support.v4.view.ViewPager
        android:id="@+id/tab_viewpager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="@android:color/white" />
</LinearLayout>

TabLayout 提供的屬性相當豐富,其中最實用的幾個是:tabIndicatorColor 決定標籤下方那條滑動指示線的顏色,tabIndicatorHeight 控制它的粗細,tabTextColor 與 tabSelectedTextColor 分別對應未選取與選取狀態的文字色,而 tabMode 可切換 fixed(等分鋪滿)與 scrollable(可橫向滾動)兩種模式。其餘屬性都能在程式碼裡動態設定,這裡不再逐一列舉。

三、Activity 端:把 Tab 與 ViewPager 綁起來

public class TabLessActivity extends AppCompatActivity {

    private TabLayout tabLayout = null;
    private ViewPager viewPager;
    private Fragment[] mFragmentArrays = new Fragment[5];
    private String[] mTabTitles = new String[5];

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.tab_layout);

        tabLayout = (TabLayout) findViewById(R.id.tablayout);
        viewPager = (ViewPager) findViewById(R.id.tab_viewpager);
        initView();
    }

    private void initView() {
        mTabTitles[0] = "推薦";
        mTabTitles[1] = "熱點";
        mTabTitles[2] = "科技";
        mTabTitles[3] = "體育";
        mTabTitles[4] = "健康";

        tabLayout.setTabMode(TabLayout.MODE_FIXED);
        // 若想調整 tab 內距,可使用:tab_title.setPadding(20,20,20,20);

        mFragmentArrays[0] = TabFragment.newInstance();
        mFragmentArrays[1] = TabFragment.newInstance();
        mFragmentArrays[2] = TabFragment.newInstance();
        mFragmentArrays[3] = TabFragment.newInstance();
        mFragmentArrays[4] = TabFragment.newInstance();

        PagerAdapter pagerAdapter = new MyViewPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(pagerAdapter);

        // 關鍵一行:將 ViewPager 與 TabLayout 綁定
        tabLayout.setupWithViewPager(viewPager);
    }
}

整段程式碼裡最關鍵的就是 tabLayout.setupWithViewPager(viewPager)。呼叫之後,TabLayout 會自動依 PagerAdapter 的標題建立標籤,並接管兩件麻煩事:點擊標籤時呼叫 ViewPager 切頁,以及滑動頁面時同步移動指示線與高亮狀態。也就是說,雙向聯動不必自己寫監聽。

四、Fragment 端:每一頁放一個列表

public class TabFragment extends Fragment {

    public static Fragment newInstance() {
        TabFragment fragment = new TabFragment();
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_tab, container, false);
        RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler);

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(new RecyclerAdapter());
        return rootView;
    }
}

每個分頁共用同一份 Fragment 實作,內部是一條由 RecyclerView 承載的長列表,卡片樣式則交給 CardView 處理。若各分頁要顯示不同資料,只要讓 newInstance() 接收一個類別參數,並在 Fragment 內依參數載入對應資料源即可。

小結

技術棧不斷演進,TabLayout 的出現讓「頂部導航」這件事從一堆自訂控件與指示器,收斂成一行 setupWithViewPager。既少寫了聯動邏輯,樣式調整也有現成屬性可用,值得作為這類需求的預設方案。

源碼下載

完整範例專案可點擊下方連結取得。

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