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

ViewPager 配 Fragment:打造類微信底部導航的頁面切換

編輯:關於 Android 程式設計

先前幾篇我們分別談過用 ViewPager 實作螢幕頁面切換與輪播,也拆解過 Fragment 的兩種建立方式,以及 Fragment 與 Activity 之間的雙向溝通。那如果把這兩個傢伙湊在一起會發生什麼事?答案是:你就能做出一個幾乎和微信一樣的底部導航介面。

原本 ViewPager 裡放的是一堆 ImageView,底部指示器也只是幾個小圓點。現在把 ImageView 換成 Fragment,把小圓點換成有圖示有文字的導航列,成品立刻不一樣了。

成品長這樣

(1)點擊下方導航按鈕,切換對應的 Fragment:

(2)直接滑動頁面,也能切換 Fragment,同時底部導航的選中狀態會同步變化:

實作步驟總覽

  • 在布局檔中配置 ViewPager 與下方導航列。
  • 依導航數量建立對應的 Fragment 布局與 Fragment 類(為日後擴充方便,建議數量對齊)。
  • 在 drawable 下用 selector 實作導航圖示與文字的形態切換。
  • 透過 FragmentPagerAdapter(v4 套件)把 ViewPager 與 Fragment 關聯起來。
  • 設定導航的點擊事件,並用 OnPageChangeListener 讓兩邊狀態互相同步。

第一步:主布局 activity_main.xml

這裡拿掉 ActionBar,改用 LinearLayout 分層堆疊:上方標題列、中間 ViewPager、下方導航列。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.administrator.viewpagerfragment.MainActivity">

    <LinearLayout
        android:background="@color/colorblack"
        android:padding="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="0dp"
            android:layout_weight="1"
            android:gravity="center_vertical"
            android:layout_height="match_parent"
            android:layout_marginLeft="5dp"
            android:text="潘侯爺微信"
            android:textSize="20sp"
            android:textColor="@color/colorWhite"/>

        <ImageView
            android:src="@mipmap/jy_drltsz_btn_addperson"
            android:adjustViewBounds="true"
            android:maxHeight="23dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/colornormal"/>

    <LinearLayout
        android:orientation="horizontal"
        android:padding="5dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:id="@+id/weixin"
            android:clickable="true"
            android:orientation="vertical"
            android:layout_width="0dp"
            android:gravity="center"
            android:layout_weight="1"
            android:layout_height="wrap_content">
            <ImageView
                android:id="@+id/weixin_img"
                android:background="@drawable/weixin_picture_selector"
                android:layout_width="30dp"
                android:layout_height="25dp" />
            <TextView
                android:id="@+id/weixin_txt"
                android:layout_width="wrap_content"
                android:gravity="center"
                android:layout_height="wrap_content"
                android:text="微信"
                android:textSize="12sp"
                android:textColor="@drawable/weixin_text_selector"/>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/contact"
            android:clickable="true"
            android:orientation="vertical"
            android:layout_width="0dp"
            android:gravity="center"
            android:layout_weight="1"
            android:layout_height="wrap_content">
            <ImageView
                android:id="@+id/contact_img"
                android:background="@drawable/txl_picture_selector"
                android:layout_width="30dp"
                android:layout_height="25dp" />
            <TextView
                android:id="@+id/contact_txt"
                android:layout_width="wrap_content"
                android:gravity="center"
                android:layout_height="wrap_content"
                android:text="通訊錄"
                android:textSize="12sp"
                android:textColor="@drawable/weixin_text_selector"/>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/find"
            android:clickable="true"
            android:orientation="vertical"
            android:layout_width="0dp"
            android:gravity="center"
            android:layout_weight="1"
            android:layout_height="wrap_content">
            <ImageView
                android:id="@+id/find_img"
                android:background="@drawable/find_picture_selector"
                android:layout_width="30dp"
                android:layout_height="25dp" />
            <TextView
                android:id="@+id/find_txt"
                android:layout_width="wrap_content"
                android:gravity="center"
                android:layout_height="wrap_content"
                android:text="發現"
                android:textSize="12sp"
                android:textColor="@drawable/weixin_text_selector"/>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/self"
            android:clickable="true"
            android:orientation="vertical"
            android:layout_width="0dp"
            android:gravity="center"
            android:layout_weight="1"
            android:layout_height="wrap_content">
            <ImageView
                android:id="@+id/self_img"
                android:background="@drawable/me_picture_selector"
                android:layout_width="30dp"
                android:layout_height="25dp" />
            <TextView
                android:id="@+id/self_txt"
                android:layout_width="wrap_content"
                android:gravity="center"
                android:layout_height="wrap_content"
                android:text="我"
                android:textSize="12sp"
                android:textColor="@drawable/weixin_text_selector"/>
        </LinearLayout>

    </LinearLayout>
</LinearLayout>

第二步:Fragment 的布局檔

四個導航對應四個 Fragment(分別是 weixin_fragment.xml、contactListFragment、findFragment、selfFragment)。雖然實作效果時只建一個也能跑,但後期擴充會很痛苦,所以建議對齊數量。以下示範其中一個:

<?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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="沒有微信消息"
        android:gravity="center"
        android:textSize="50sp"/>

</LinearLayout>

第三步:用 selector 切換導航外觀

文字部分只是換色,圖片部分則需要準備選中與未選中兩張圖。

(1)文字顏色 wenxin_text_selector.xml

這裡刻意用 state_selected 而不是 state_checked:因為導航項的 clickable 是設在外層 LinearLayout 上,而不是內部的 TextView/ImageView,用 selected 讓程式碼端的呼叫更直觀。

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:color="@color/colorpressed" android:state_selected="true"/>
    <item android:color="@color/colornormal" android:state_selected="false" />
</selector>

(2)圖片 weixin_picture_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:drawable="@mipmap/weixin_pressed" android:state_selected="true"/>
    <item android:drawable="@mipmap/weixin_normal" android:state_selected="false" />
</selector>

第四步:Fragment 的 Java 類

建議繼承 android.support.v4.app.Fragment,因為後面要用的 FragmentPagerAdapter 屬於 v4 套件,保持一致比較不會出問題。四個 Fragment 對應四個類,這裡示範一個:

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class WeixinFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.weixin_fragment, container, false);
        return view;
    }
}

第五步:MainActivity 的功能實作

整支程式碼的骨架就是三件事:初始化 View、綁定監聽、處理狀態同步。為了讓流程清楚,這裡沒有過度封裝重複的 setSelected 邏輯:

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.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    // 存放 Fragment 的集合
    private ArrayList<Fragment> fragments;

    // 四個導航對應的 Fragment
    WeixinFragment weixinFragment;
    ContactListFragment contactListFragment;
    FindFragment findFragment;
    SelfFragment selfFragment;

    private ViewPager viewPager;
    FragmentManager fragmentManager;

    // 導航列的四個容器
    private LinearLayout weixin, contact, find, self;

    // 導航列中的圖示與文字
    private ImageView weixin_img, contact_img, find_img, self_img;
    private TextView weixin_txt, contact_txt, find_txt, self_txt;

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

        initView();
        initListener();

        // 設定預設選中的頁與導航狀態
        viewPager.setCurrentItem(0);
        weixin_img.setSelected(true);
        weixin_txt.setSelected(true);
    }

    private void initListener() {
        // 四大導航的點擊監聽
        weixin.setOnClickListener(this);
        contact.setOnClickListener(this);
        find.setOnClickListener(this);
        self.setOnClickListener(this);

        // ViewPager 的頁面變化監聽
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                // 依位置決定哪個導航處於選中狀態
                viewPager.setCurrentItem(position);
                switch (position) {
                    case 0:
                        weixin_img.setSelected(true); weixin_txt.setSelected(true);
                        contact_img.setSelected(false); contact_txt.setSelected(false);
                        find_img.setSelected(false); find_txt.setSelected(false);
                        self_img.setSelected(false); self_txt.setSelected(false);
                        break;
                    case 1:
                        weixin_img.setSelected(false); weixin_txt.setSelected(false);
                        contact_img.setSelected(true); contact_txt.setSelected(true);
                        find_img.setSelected(false); find_txt.setSelected(false);
                        self_img.setSelected(false); self_txt.setSelected(false);
                        break;
                    case 2:
                        weixin_img.setSelected(false); weixin_txt.setSelected(false);
                        contact_img.setSelected(false); contact_txt.setSelected(false);
                        find_img.setSelected(true); find_txt.setSelected(true);
                        self_img.setSelected(false); self_txt.setSelected(false);
                        break;
                    case 3:
                        weixin_img.setSelected(false); weixin_txt.setSelected(false);
                        contact_img.setSelected(false); contact_txt.setSelected(false);
                        find_img.setSelected(false); find_txt.setSelected(false);
                        self_img.setSelected(true); self_txt.setSelected(true);
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    private void initView() {
        viewPager = (ViewPager) findViewById(R.id.viewPager);

        weixinFragment = new WeixinFragment();
        contactListFragment = new ContactListFragment();
        findFragment = new FindFragment();
        selfFragment = new SelfFragment();

        fragments = new ArrayList<>();
        fragments.add(weixinFragment);
        fragments.add(contactListFragment);
        fragments.add(findFragment);
        fragments.add(selfFragment);

        fragmentManager = getSupportFragmentManager();
        // 為 ViewPager 設定 Adapter 來部署 Fragments
        viewPager.setAdapter(new MyFragmentPagerAdapter(fragmentManager));

        weixin = (LinearLayout) findViewById(R.id.weixin);
        contact = (LinearLayout) findViewById(R.id.contact);
        find = (LinearLayout) findViewById(R.id.find);
        self = (LinearLayout) findViewById(R.id.self);

        weixin_img = (ImageView) findViewById(R.id.weixin_img);
        contact_img = (ImageView) findViewById(R.id.contact_img);
        find_img = (ImageView) findViewById(R.id.find_img);
        self_img = (ImageView) findViewById(R.id.self_img);

        weixin_txt = (TextView) findViewById(R.id.weixin_txt);
        contact_txt = (TextView) findViewById(R.id.contact_txt);
        find_txt = (TextView) findViewById(R.id.find_txt);
        self_txt = (TextView) findViewById(R.id.self_txt);
    }

    /**
     * 導航列點擊事件:本質上就是改四組 ImageView/TextView 的選中狀態,
     * 再搭配 drawable 中的 selector 完成視覺切換
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.weixin:
                viewPager.setCurrentItem(0);
                weixin_img.setSelected(true); weixin_txt.setSelected(true);
                contact_img.setSelected(false); contact_txt.setSelected(false);
                find_img.setSelected(false); find_txt.setSelected(false);
                self_img.setSelected(false); self_txt.setSelected(false);
                break;
            case R.id.contact:
                viewPager.setCurrentItem(1);
                weixin_img.setSelected(false); weixin_txt.setSelected(false);
                contact_img.setSelected(true); contact_txt.setSelected(true);
                find_img.setSelected(false); find_txt.setSelected(false);
                self_img.setSelected(false); self_txt.setSelected(false);
                break;
            case R.id.find:
                viewPager.setCurrentItem(2);
                weixin_img.setSelected(false); weixin_txt.setSelected(false);
                contact_img.setSelected(false); contact_txt.setSelected(false);
                find_img.setSelected(true); find_txt.setSelected(true);
                self_img.setSelected(false); self_txt.setSelected(false);
                break;
            case R.id.self:
                viewPager.setCurrentItem(3);
                weixin_img.setSelected(false); weixin_txt.setSelected(false);
                contact_img.setSelected(false); contact_txt.setSelected(false);
                find_img.setSelected(false); find_txt.setSelected(false);
                self_img.setSelected(true); self_txt.setSelected(true);
                break;
        }
    }

    // FragmentPagerAdapter 的實作
    class MyFragmentPagerAdapter extends FragmentPagerAdapter {

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

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

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

兩個實務上的優化方向

第一,onPageSelected 與 onClick 裡那四段 setSelected 幾乎一模一樣,實際專案請抽成一個 updateTabState(int position) 方法,程式碼量能少一半以上。第二,若使用 BottomNavigationView 這類現成元件,Google 已經內建了與 ViewPager 的聯動支援,能省下不少樣板;但在需要高度自訂外觀的場景,本文這種手刻方式反而更好控制。

以上就是這次的完整實作,希望對你的專案有幫助。

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