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

TabLayout + ViewPager 聯動實戰:從依賴配置到 Adapter 完善

編輯:關於 Android 開發

TabLayout 與 ViewPager 是 Android 裡最經典的「頂部標簽 + 左右滑動」組合。本文按實際開發順序走一遍,包含幾個容易踩坑的細節。

一、實現思路

1. 添加依賴

compile 'com.android.support:support-v4:23.4.0'
compile 'com.android.support:design:23.4.0'

也可以把 support-v4 換成 appcompat-v7,因為後者本身就依賴前者:

compile 'com.android.support:appcompat-v7:23.4.0'

更多說明可參考官方 Support Library 文檔。

2. 佈局中放入 TabLayout 與 ViewPager

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/tabLayoutBackground"
        app:tabMode="scrollable"
        app:tabTextColor="@color/color_white"
        app:tabSelectedTextColor="@color/tabSelectedText"
        app:tabIndicatorHeight="3dp"
        app:tabIndicatorColor="@color/color_white"/>

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

關鍵屬性說明:

  • tabMode 有兩個取值。scrollable 適用於標簽較多的場景,可橫向滾動;fixed 會讓所有標簽平均分布在屏幕寬度上,因此標簽數量不能多、文字也不能長,否則顯示不全。
  • tabIndicatorHeight 與 tabIndicatorColor 控制選中標簽下方那條指示條的高度與顏色。指示條只在對應 tab 被選中時顯示。

3. 獲取 View 對象

TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);

4. 創建 Adapter 並綁定

TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);

ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);   // 一行完成聯動

setupWithViewPager() 會自動完成標簽與頁面的雙向同步:點標簽切頁、滑頁面換標簽,都不用自己寫監聽。

FragmentPagerAdapter 還是 FragmentStatePagerAdapter?

  • FragmentPagerAdapter:適合頁數較少的場景。只要用戶還停留在當前 Activity,已創建的 Fragment 都不會被銷毀,因此內存佔用較高。
  • FragmentStatePagerAdapter:工作原理類似 ListView,不可見的 Fragment 會被銷毀,只保留其狀態(Bundle),內存更友好。

因為示例使用的是 v4 兼容包下的 Fragment,所以獲取 FragmentManager 要用 getSupportFragmentManager()。

二、完善 Adapter

1. 重寫三個核心方法

public class ViewPagerAdapter extends FragmentStatePagerAdapter {

    private String[] titles;
    private ArrayList<ViewPagerFragment> viewPagerFragments;

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

    public void setTitles(String[] titles) { this.titles = titles; }

    public void setFragments(ArrayList<ViewPagerFragment> fragments) {
        this.viewPagerFragments = fragments;
    }

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

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

    @Override
    public CharSequence getPageTitle(int position) {
        return titles[position];      // 標簽文字由此提供
    }
}

2. 準備標題數據

private String[] mTitles =
        new String[]{"語文", "英語", "數學", "物理", "生物", "化學", "地理", "政治", "歷史"};

3. 創建 Fragment 子類

public class ViewPagerFragment extends Fragment {
    private static final String KEY = "extra";
    private String mMessage;

    public static ViewPagerFragment newInstance(String extra) {
        Bundle args = new Bundle();
        args.putString(KEY, extra);
        ViewPagerFragment fragment = new ViewPagerFragment();
        fragment.setArguments(args);
        return fragment;
    }
}

4. 生成 Fragment 集合並傳給 Adapter

private ArrayList<ViewPagerFragment> mViewPagerFragments = new ArrayList<>();

for (int i = 0; i < mTitles.length; i++) {
    mViewPagerFragments.add(ViewPagerFragment.newInstance(mTitles[i]));
}

viewPagerAdapter.setTitles(mTitles);
viewPagerAdapter.setFragments(mViewPagerFragments);

三、完善 Fragment

fragment_view_pager_item.xml

<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:id="@+id/fragment_text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"/>
</LinearLayout>

Fragment 代碼

public class ViewPagerFragment extends Fragment {

    private static final String KEY = "extra";
    private String mMessage;

    public static ViewPagerFragment newInstance(String extra) { /* 同上 */ }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mMessage = bundle.getString(KEY);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_view_pager_item, container, false);
        TextView textView = (TextView) view.findViewById(R.id.fragment_text);
        textView.setText(mMessage);
        return view;
    }
}

兩個方法的職責需要區分清楚:

  • onCreate() 在 Fragment 創建時調用,適合做狀態信息的初始化,便於日後恢復。
  • onCreateView() 在首次加載視圖時調用,負責加載並初始化視圖,返回值必須是該 Fragment 佈局的根視圖。

其中 inflate() 的第三個參數表示「是否把加載進來的佈局立即添加到 container 這個 ViewGroup 中」。Fragment 框架內部已經幫我們處理了附加邏輯,因此這裡必須傳 false,否則會拋 IllegalStateException。

四、效果

五、補充

新版項目中建議改用 com.google.android.material:material 提供的 TabLayout,並搭配 ViewPager2(基於 RecyclerView,默認支持左右滑動與更合理的銷毀策略)。若只是標簽與頁面聯動,TabLayoutMediator 一行即可替代 setupWithViewPager()。

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