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

Android 專案拆解:用 ViewPager + Fragment 實作底部 Tab 導覽

編輯:關於 Android 程式設計

很多 App 都需要一個底部導覽列,滑動或點擊都能切換上方內容,效果如下:

這個效果目前的主流做法是 ViewPager 搭配 Fragment。如果對 Fragment 還不熟,建議先補一下官方文件的觀念再回來。

專案結構如下:

一、版面配置

主配置非常單純,就是一個 ViewPager 加上一條 LinearLayout 作為底部選單,裡面放四個 TextView 與一條用來滑動的白色指示線 ImageView。各頁面的配置 lay1、lay2、lay3… 都是普通配置檔,就不佔篇幅了。

二、MainActivity

package com.vatty.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.content.res.Resources;
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.util.Log;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends FragmentActivity {

    private static final String TAG = "MainActivity";

    private ViewPager mPager;
    private ArrayList<Fragment> fragmentsList;

    private ImageView ivBottomLine;
    private TextView tv_tab_1, tv_tab_2, tv_tab_3, tv_tab_4;

    private int currIndex = 0;      // 目前所在頁
    private int bottomLineWidth;    // 白色指示線寬度
    private int offset = 0;         // 每格左側的間距
    private int position_one;
    private int position_two;
    private int position_three;

    private Resources resources;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);

        resources = getResources();
        InitWidth();      // 先算好寬度相關數值
        InitTextView();   // 底部選單
        InitViewPager();  // 內容頁
    }

    /** 取得底部控制項並掛上監聽 */
    private void InitTextView() {
        tv_tab_1 = (TextView) findViewById(R.id.tv_tab_1);
        tv_tab_2 = (TextView) findViewById(R.id.tv_tab_2);
        tv_tab_3 = (TextView) findViewById(R.id.tv_tab_3);
        tv_tab_4 = (TextView) findViewById(R.id.tv_tab_4);

        tv_tab_1.setOnClickListener(new MyOnClickListener(0));
        tv_tab_2.setOnClickListener(new MyOnClickListener(1));
        tv_tab_3.setOnClickListener(new MyOnClickListener(2));
        tv_tab_4.setOnClickListener(new MyOnClickListener(3));
    }

    /** 初始化 ViewPager 與各頁 Fragment */
    private void InitViewPager() {
        mPager = (ViewPager) findViewById(R.id.vPager);
        fragmentsList = new ArrayList<Fragment>();

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("userid", "小洪");
        paramMap.put("age", 23);

        Map<String, Object> paramMap2 = new HashMap<String, Object>();
        paramMap2.put("userid", "vatty");
        paramMap2.put("age", 24);

        Map<String, Object> paramMap3 = new HashMap<String, Object>();
        paramMap3.put("userid", "小明");
        paramMap3.put("age", 25);

        Map<String, Object> paramMap4 = new HashMap<String, Object>();
        paramMap4.put("userid", "hongshengpeng.com");
        paramMap4.put("age", 26);

        Fragment activityFragment = TestFragment.newInstance("Hello Activity.", paramMap);
        Fragment groupFragment = TestFragment.newInstance("Hello Group.", paramMap2);
        Fragment friendsFragment = TestFragment.newInstance("Hello Friends.", paramMap3);
        Fragment chatFragment = TestFragment.newInstance("Hello Chat.", paramMap4);

        fragmentsList.add(activityFragment);
        fragmentsList.add(groupFragment);
        fragmentsList.add(friendsFragment);
        fragmentsList.add(chatFragment);

        mPager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager(), fragmentsList));
        mPager.setCurrentItem(0);
        mPager.setOnPageChangeListener(new MyOnPageChangeListener());
    }

    /** 取得底部控制項的寬度資訊 */
    private void InitWidth() {
        ivBottomLine = (ImageView) findViewById(R.id.iv_bottom_line);
        bottomLineWidth = ivBottomLine.getLayoutParams().width;
        Log.d(TAG, "cursor imageview width = " + bottomLineWidth);

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenW = dm.widthPixels;

        // 螢幕四等分,算出白色滑條外側的間距
        offset = (int) ((screenW / 4.0 - bottomLineWidth) / 2);
        Log.i(TAG, "offset = " + offset);

        position_one = (int) (screenW / 4.0);
        position_two = position_one * 2;
        position_three = position_one * 3;
    }

    /** 共用的點擊監聽,用 index 區分點了哪一格 */
    public class MyOnClickListener implements View.OnClickListener {
        private int index = 0;

        public MyOnClickListener(int i) {
            index = i;
        }

        @Override
        public void onClick(View v) {
            mPager.setCurrentItem(index);
        }
    }

    /** 換頁時播放指示線動畫並切換文字顏色 */
    public class MyOnPageChangeListener implements OnPageChangeListener {

        @Override
        public void onPageSelected(int index) {
            Animation animation = null;
            switch (index) {
                case 0:
                    if (currIndex == 1) {
                        animation = new TranslateAnimation(position_one, 0, 0, 0);
                        tv_tab_2.setTextColor(resources.getColor(R.color.lightwhite));
                    } else if (currIndex == 2) {
                        animation = new TranslateAnimation(position_two, 0, 0, 0);
                        tv_tab_3.setTextColor(resources.getColor(R.color.lightwhite));
                    } else if (currIndex == 3) {
                        animation = new TranslateAnimation(position_three, 0, 0, 0);
                        tv_tab_4.setTextColor(resources.getColor(R.color.lightwhite));
                    }
                    tv_tab_1.setTextColor(resources.getColor(R.color.white));
                    break;

                case 1:
                    if (currIndex == 0) {
                        animation = new TranslateAnimation(0, position_one, 0, 0);
                        tv_tab_1.setTextColor(resources.getColor(R.color.lightwhite));
                    } else if (currIndex == 2) {
                        animation = new TranslateAnimation(position_two, position_one, 0, 0);
                        tv_tab_3.setTextColor(resources.getColor(R.color.lightwhite));
                    } else if (currIndex == 3) {
                        animation = new TranslateAnimation(position_three, position_one, 0, 0);
                        tv_tab_4.setTextColor(resources.getColor(R.color.lightwhite));
                    }
                    tv_tab_2.setTextColor(resources.getColor(R.color.white));
                    break;

                case 2:
                    if (currIndex == 0) {
                        animation = new TranslateAnimation(0, position_two, 0, 0);
                        tv_tab_1.setTextColor(resources.getColor(R.color.lightwhite));
                    } else if (currIndex == 1) {
                        animation = new TranslateAnimation(position_one, position_two, 0, 0);
                        tv_tab_2.setTextColor(resources.getColor(R.color.lightwhite));
                    } else if (currIndex == 3) {
                        animation = new TranslateAnimation(position_three, position_two, 0, 0);
                        tv_tab_4.setTextColor(resources.getColor(R.color.lightwhite));
                    }
                    tv_tab_3.setTextColor(resources.getColor(R.color.white));
                    break;

                case 3:
                    if (currIndex == 0) {
                        animation = new TranslateAnimation(0, position_three, 0, 0);
                        tv_tab_1.setTextColor(resources.getColor(R.color.lightwhite));
                    } else if (currIndex == 1) {
                        animation = new TranslateAnimation(position_one, position_three, 0, 0);
                        tv_tab_2.setTextColor(resources.getColor(R.color.lightwhite));
                    } else if (currIndex == 2) {
                        animation = new TranslateAnimation(position_two, position_three, 0, 0);
                        tv_tab_3.setTextColor(resources.getColor(R.color.lightwhite));
                    }
                    tv_tab_4.setTextColor(resources.getColor(R.color.white));
                    break;
            }

            currIndex = index;

            animation.setFillAfter(true);   // 動畫結束後保留終態
            animation.setDuration(300);
            ivBottomLine.startAnimation(animation);
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) { }

        @Override
        public void onPageScrollStateChanged(int arg0) { }
    }
}

這個類別做的就是初始化:載入版面、取得控制項、設定 Adapter、掛上監聽。註解已寫得相當完整,這裡不再贅述。

三、Fragment 模組

每個 Tab 對應一個 TestFragment,透過 newInstance 傳入參數。由於 Fragment 必須能被系統重建,直接透過建構子傳值並不可靠,因此這裡把 Map 包成 Serializable 放進 Bundle 的 setArguments 中。

package com.vatty.activity;

import java.util.ArrayList;
import java.util.Map;

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

import com.vatty.adapter.ContactAdapter;
import com.vatty.model.Contact;

public class TestFragment extends Fragment {

    private Map<String, Object> maplist;

    /** 建立帶參數的新 Fragment */
    static TestFragment newInstance(String s, Map<String, Object> map) {
        TestFragment newFragment = new TestFragment();
        SerializableMap myMap = new SerializableMap();
        myMap.setMap(map);

        Bundle bundle = new Bundle();
        bundle.putSerializable("map", myMap);
        newFragment.setArguments(bundle);
        return newFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        SerializableMap serializableMap = (SerializableMap) bundle.getSerializable("map");
        maplist = serializableMap.getMap();
    }

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

        ListView lv = (ListView) view.findViewById(R.id.listView3);
        ContactAdapter hc = new ContactAdapter(getActivity().getApplicationContext(), getContact());
        lv.setAdapter(hc);
        lv.setCacheColorHint(0);
        return view;
    }

    private ArrayList<Contact> getContact() {
        ArrayList<Contact> hcList = new ArrayList<Contact>();
        for (int i = 0; i < 10; i++) {
            Contact c0 = new Contact();
            c0.setTxPath(R.drawable.more_game);
            c0.setName(maplist.get("userid") + " 年齡:" + maplist.get("age"));
            hcList.add(c0);
        }
        return hcList;
    }
}

其餘如 Adapter、Adapter 的 SerializableMap 包裝類別,寫法與平常開發沒有差別。

四、幾個可以更好的地方

  • 四個 case 分支幾乎是同一套邏輯的複製,可抽成 animateTo(from, to) 之類的方法,程式碼量能少一半。
  • 指示線位置建議改用 ViewPager 的滑動比例即時插值,讓它跟手移動,視覺會比「切頁後才播動畫」順得多。
  • 若想支援更多 Tab,把硬編碼的 position_one/two/three 換成陣列與迴圈會更好擴充。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved