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

用 ViewPager 與 Fragment 實作頂部導航滑動切換

編輯:關於 Android 程式設計

專案裡很常需要「左右滑動切換頁面」的效果,微信的主頁就是最典型的例子。本文帶你認識 ViewPager,並用一個完整範例把頂部導航條跟手滑動的效果做出來。

一、ViewPager 是什麼

官方對它的定義是:

大意是:這是一個橫向的頁面容器,使用者可以左右滑動翻頁;要提供內容,需要實作 PagerAdapter。

ViewPager 常與 Fragment 搭配使用,因為 Fragment 天生自帶生命週期,管理每頁的存廢變得容易許多。官方為此準備了兩個現成的 Adapter:FragmentPagerAdapter 與 FragmentStatePagerAdapter。本文採用前者。

二、效果預覽

三、程式碼實作

1. 主布局 activity_main.xml

<LinearLayout 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"
    android:orientation="vertical">

    <include layout="@layout/activity_main_top_tab" />

</LinearLayout>

布局裡使用的 android.support.v4.view.ViewPager 需要 android-support-v4.jar,正常情況下 ADT / Gradle 會自動引入。

2. 頂部導航 activity_main_top_tab.xml

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

    <LinearLayout
        android:id="@+id/id_switch_tab_ll"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:baselineAligned="false"
        android:orientation="horizontal">

        <LinearLayout
            android:id="@+id/id_tab_chat_ll"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/guide_round_selector"
            android:gravity="center"
            android:orientation="horizontal"
            android:padding="10dip">

            <TextView
                android:id="@+id/id_chat_tv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="聊天"
                android:textColor="#0000FF"
                android:textSize="15dip" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/id_tab_friend_ll"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/guide_round_selector"
            android:clickable="true"
            android:gravity="center"
            android:orientation="horizontal"
            android:padding="10dip"
            android:saveEnabled="false">

            <TextView
                android:id="@+id/id_friend_tv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="好友"
                android:textColor="#000000"
                android:textSize="15dip" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/id_tab_contacts_ll"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/guide_round_selector"
            android:focusable="false"
            android:gravity="center"
            android:orientation="horizontal"
            android:padding="10dip">

            <TextView
                android:id="@+id/id_contacts_tv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="通訊錄"
                android:textColor="#000000"
                android:textSize="15dip" />
        </LinearLayout>
    </LinearLayout>

    <ImageView
        android:id="@+id/id_tab_line_iv"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:background="@drawable/tab_selected_pressed_holo"
        android:contentDescription="tab" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#000000" />

</LinearLayout>

這裡的 id_tab_line_iv 就是那條會跟著手指移動的滑塊,它的 leftMargin 會在後續程式碼中被動態改寫。

3. Fragment 布局

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

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="聊天界面"
        android:textColor="#FF0000"
        android:textSize="20sp" />

</LinearLayout>

activity_tab_contacts.xml、activity_tab_friend.xml 結構相同,只換文字。

4. MainActivity.java

package com.example.viewpagerdemo;

import java.util.ArrayList;
import java.util.List;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends FragmentActivity {

    private List<Fragment> mFragmentList = new ArrayList<Fragment>();
    private FragmentAdapter mFragmentAdapter;
    private ViewPager mPageVp;

    private TextView mTabChatTv, mTabContactsTv, mTabFriendTv;
    private ImageView mTabLineIv;

    private ChatFragment mChatFg;
    private FriendFragment mFriendFg;
    private ContactsFragment mContactsFg;

    private int currentIndex;
    private int screenWidth;

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

        findById();
        init();
        initTabLineWidth();
    }

    private void findById() {
        mTabContactsTv = (TextView) this.findViewById(R.id.id_contacts_tv);
        mTabChatTv = (TextView) this.findViewById(R.id.id_chat_tv);
        mTabFriendTv = (TextView) this.findViewById(R.id.id_friend_tv);
        mTabLineIv = (ImageView) this.findViewById(R.id.id_tab_line_iv);
        mPageVp = (ViewPager) this.findViewById(R.id.id_page_vp);
    }

    private void init() {
        mFriendFg = new FriendFragment();
        mContactsFg = new ContactsFragment();
        mChatFg = new ChatFragment();

        mFragmentList.add(mChatFg);
        mFragmentList.add(mFriendFg);
        mFragmentList.add(mContactsFg);

        mFragmentAdapter = new FragmentAdapter(getSupportFragmentManager(), mFragmentList);
        mPageVp.setAdapter(mFragmentAdapter);
        mPageVp.setCurrentItem(0);

        mPageVp.setOnPageChangeListener(new OnPageChangeListener() {

            /** state 有三種:0 什麼都沒做,1 正在滑動,2 滑動完畢 */
            @Override
            public void onPageScrollStateChanged(int state) { }

            /**
             * position      : 當前所在頁面
             * offset        : 當前頁面偏移的百分比(0~1)
             * offsetPixels  : 當前頁面偏移的像素數
             */
            @Override
            public void onPageScrolled(int position, float offset, int offsetPixels) {
                LinearLayout.LayoutParams lp =
                        (LinearLayout.LayoutParams) mTabLineIv.getLayoutParams();
                int tabWidth = screenWidth / 3;

                // 用 currentIndex、position 與 offset 三者共同決定滑塊左邊距
                // 三個頁面的滑動情境:0->1、1->2、2->1、1->0
                if (currentIndex == 0 && position == 0) {          // 0 -> 1
                    lp.leftMargin = (int) (offset * tabWidth + currentIndex * tabWidth);
                } else if (currentIndex == 1 && position == 0) {  // 1 -> 0
                    lp.leftMargin = (int) (-(1 - offset) * tabWidth + currentIndex * tabWidth);
                } else if (currentIndex == 1 && position == 1) {  // 1 -> 2
                    lp.leftMargin = (int) (offset * tabWidth + currentIndex * tabWidth);
                } else if (currentIndex == 2 && position == 1) {  // 2 -> 1
                    lp.leftMargin = (int) (-(1 - offset) * tabWidth + currentIndex * tabWidth);
                }
                mTabLineIv.setLayoutParams(lp);
            }

            @Override
            public void onPageSelected(int position) {
                resetTextView();
                switch (position) {
                    case 0:
                        mTabChatTv.setTextColor(Color.BLUE);
                        break;
                    case 1:
                        mTabFriendTv.setTextColor(Color.BLUE);
                        break;
                    case 2:
                        mTabContactsTv.setTextColor(Color.BLUE);
                        break;
                }
                currentIndex = position;
            }
        });
    }

    /** 滑塊寬度設為螢幕的 1/3(依 Tab 數量而定) */
    private void initTabLineWidth() {
        DisplayMetrics dpMetrics = new DisplayMetrics();
        getWindow().getWindowManager().getDefaultDisplay().getMetrics(dpMetrics);
        screenWidth = dpMetrics.widthPixels;

        LinearLayout.LayoutParams lp =
                (LinearLayout.LayoutParams) mTabLineIv.getLayoutParams();
        lp.width = screenWidth / 3;
        mTabLineIv.setLayoutParams(lp);
    }

    private void resetTextView() {
        mTabChatTv.setTextColor(Color.BLACK);
        mTabFriendTv.setTextColor(Color.BLACK);
        mTabContactsTv.setTextColor(Color.BLACK);
    }
}

這裡有四點要注意。

第一,MainActivity 必須繼承 FragmentActivity(或 AppCompatActivity),才能使用支援庫的 Fragment 體系。

第二,滑塊寬度在 initTabLineWidth() 裡設定為螢幕寬度的 1/3,因為本例固定三個頁面。頁面數量可變時,這裡要改成動態計算。

第三,onPageScrolled() 是捕捉滑動的核心。它給出的 position 是「當前頁」而非「目標頁」,這點容易誤解。程式碼之所以要分成四個 if 分支,是因為滑動方向有兩種(前進與後退),而 offset 永遠從 0 遞增到 1,所以需要依方向決定該做加法還是「1 減 offset」。

第四,範例中 findById() 找的是 R.id.id_page_vp,但布局檔裡並沒有這個 ViewPager——實作時記得把 ViewPager 補進 activity_main_top_tab.xml 或主布局,否則會拿到 null。

5. FragmentAdapter.java

package com.example.viewpagerdemo;

import java.util.ArrayList;
import java.util.List;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class FragmentAdapter extends FragmentPagerAdapter {

    private List<Fragment> fragmentList = new ArrayList<Fragment>();

    public FragmentAdapter(FragmentManager fm, List<Fragment> fragmentList) {
        super(fm);
        this.fragmentList = fragmentList;
    }

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

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

6. ChatFragment.java

package com.example.viewpagerdemo;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class ChatFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        return inflater.inflate(R.layout.activity_tab_chat, container, false);
    }
}

ContactsFragment 與 FriendFragment 寫法相同。

幾點延伸思考

滑塊跟手的原理其實很單純:把「頁面偏移百分比」線性映射成「滑塊左邊距」。理解之後,滑塊也可以用 offsetPixels 直接算,不必繞 currentIndex 判斷方向——因為 position + offset 本身就是滑塊應該停留的浮點位置,乘以單格寬度即可。這個寫法不僅短,而且頁面數量改成任意值都不用動。

另外,onPageScrolled 在滑動過程中會被高頻呼叫,方法內每次都重新 getLayoutParams() 並 setLayoutParams() 會觸發重複的測量與布局。把 LayoutParams 物件在初始化時取出並快取,滑動中只改 leftMargin 數值,最後一次再套用,會順暢一些。

最後,滑塊背景那張 tab_selected_pressed_holo 的寬度必須與程式計算的單格寬度一致,否則視覺上會對不齊。這是這類效果最常見的顯示異常來源。

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