1. 程式人生 > 實用技巧 >吳裕雄--天生自然ANDROID開發學習:2.6.3 ViewPager的簡單使用

吳裕雄--天生自然ANDROID開發學習:2.6.3 ViewPager的簡單使用

官方API文件:ViewPager:http://androiddoc.qiniudn.com/reference/android/support/v4/view/ViewPager.html
1.ViewPager的簡單介紹
FragmentPageAdapter:和PagerAdapter一樣,只會快取當前的Fragment以及左邊一個,右邊 一個,即總共會快取3個Fragment而已,假如有1,2,3,4四個頁面:
處於1頁面:快取1,2
處於2頁面:快取1,2,3
處於3頁面:銷燬1頁面,快取2,3,4
處於4頁面:銷燬2頁面,快取3,4
FragmentStatePagerAdapter:當Fragment對使用者不 見得時,整個Fragment會被銷燬, 只會儲存Fragment的狀態!而在頁面需要重新顯示的時候,會生成新的頁面!
綜上,FragmentPageAdapter適合固定的頁面較少的場合;而FragmentStatePagerAdapter則適合 於頁面較多或者頁面內容非常複雜(需佔用大量記憶體)的情況
2.PagerAdapter的使用
getCount():獲得viewpager中有多少個view
destroyItem():移除一個給定位置的頁面。介面卡有責任從容器中刪除這個檢視。 這是為了確保在finishUpdate(viewGroup)返回時檢視能夠被移除。
instantiateItem(): ①將給定位置的view新增到ViewGroup(容器)中,建立並顯示出來 ②返回一個代表新增頁面的Object(key),通常都是直接返回view本身就可以了,當然你也可以 自定義自己的key,但是key和每個view要一一對應的關係
isViewFromObject(): 判斷instantiateItem(ViewGroup, int)函式所返回來的Key與一個頁面檢視是否是 代表的同一個檢視(即它倆是否是對應的,對應的表示同一個View),通常我們直接寫 return view == object

程式碼寫起來也是非常簡單的:首先是每個View的佈局,一式三份,另外兩個View一樣:

view_one.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFBA55"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="第一個Page"
        android:textColor="#000000"
        android:textSize="18sp"
        android:textStyle="bold" />
</LinearLayout>  
然後編寫一個自定義個的PagerAdapter:

MyPagerAdapter.java:

public class MyPagerAdapter extends PagerAdapter {
    private ArrayList<View> viewLists;

    public MyPagerAdapter() {
    }

    public MyPagerAdapter(ArrayList<View> viewLists) {
        super();
        this.viewLists = viewLists;
    }

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

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        container.addView(viewLists.get(position));
        return viewLists.get(position);
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView(viewLists.get(position));
    }
}
接著到Activity了,和以前學的ListView非常類似:

OneActivity.java:

public class OneActivity extends AppCompatActivity{

    private ViewPager vpager_one;
    private ArrayList<View> aList;
    private MyPagerAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_one);
        vpager_one = (ViewPager) findViewById(R.id.vpager_one);

        aList = new ArrayList<View>();
        LayoutInflater li = getLayoutInflater();
        aList.add(li.inflate(R.layout.view_one,null,false));
        aList.add(li.inflate(R.layout.view_two,null,false));
        aList.add(li.inflate(R.layout.view_three,null,false));
        mAdapter = new MyPagerAdapter(aList);
        vpager_one.setAdapter(mAdapter);
    }
}
使用示例2:標題欄——PagerTitleStrip與PagerTabStrip
PagerTitleStrip所在Activtiy的佈局: activity_two.xml:

<LinearLayout xmlns:android="http://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="48dp"
        android:background="#CCFF99"
        android:gravity="center"
        android:text="PagerTitleStrip效果演示"
        android:textColor="#000000"
        android:textSize="18sp" />

    <android.support.v4.view.ViewPager
        android:id="@+id/vpager_two"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center">

        <android.support.v4.view.PagerTitleStrip
            android:id="@+id/pagertitle"
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:layout_gravity="top"
            android:textColor="#FFFFFF" />
   </android.support.v4.view.ViewPager>

</LinearLayout> 
而PagerTabStrip所在的佈局:

activity_three.xml:

<LinearLayout xmlns:android="http://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="35dp"
        android:background="#C0C080"
        android:gravity="center"
        android:text="PagerTabStrip效果演示"
        android:textSize="18sp" />
        
    <android.support.v4.view.ViewPager
        android:id="@+id/vpager_three"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center">

        <android.support.v4.view.PagerTabStrip
            android:id="@+id/pagertitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="top" />
     </android.support.v4.view.ViewPager>
</LinearLayout>
MyPagerAdapter2.java:

/**
 * Created by Jay on 2015/10/8 0008.
 */
public class MyPagerAdapter2 extends PagerAdapter {
    private ArrayList<View> viewLists;
    private ArrayList<String> titleLists;

    public MyPagerAdapter2() {}
    public MyPagerAdapter2(ArrayList<View> viewLists,ArrayList<String> titleLists)
    {
        this.viewLists = viewLists;
        this.titleLists = titleLists;
    }

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

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        container.addView(viewLists.get(position));
        return viewLists.get(position);
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView(viewLists.get(position));
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return titleLists.get(position);
    }
}
最後是Activity部分,兩個都是一樣的:

TwoActivity.java:

/**
 * Created by Jay on 2015/10/8 0008.
 */
public class TwoActivity extends AppCompatActivity {

    private ViewPager vpager_two;
    private ArrayList<View> aList;
    private ArrayList<String> sList;
    private MyPagerAdapter2 mAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_two);
        vpager_two = (ViewPager) findViewById(R.id.vpager_two);
        aList = new ArrayList<View>();
        LayoutInflater li = getLayoutInflater();
        aList.add(li.inflate(R.layout.view_one,null,false));
        aList.add(li.inflate(R.layout.view_two,null,false));
        aList.add(li.inflate(R.layout.view_three, null, false));
        sList = new ArrayList<String>();
        sList.add("橘黃");
        sList.add("淡黃");
        sList.add("淺棕");
        mAdapter = new MyPagerAdapter2(aList,sList);
        vpager_two.setAdapter(mAdapter);
    }
}
使用示例3:ViewPager實現TabHost的效果:
執行效果圖:



實現邏輯解析:

下面我們來講解下實現上述效果的邏輯,然後貼程式碼:

首先是佈局:頂部一個LinearLayout,包著三個TextView,weight屬性都為1,然後下面跟著 一個滑塊的ImageView,我們設定寬度為match_parent;最底下是我們的ViewPager,這裡可能 有兩個屬性你並不認識,一個是:flipInterval:這個是指定View動畫間的時間間隔的!
而persistentDrawingCache:則是設定控制元件的繪製快取策略,可選值有四個:
none:不在記憶體中儲存繪圖快取;
animation:只儲存動畫繪圖快取;
scrolling:只儲存滾動效果繪圖快取;
all:所有的繪圖快取都應該儲存在記憶體中;
可以同時用2個,animation|scrolling這樣~
佈局程式碼:activity_four.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="48dp"
        android:background="#FFFFFF">

        <TextView
            android:id="@+id/tv_one"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1.0"
            android:gravity="center"
            android:text="橘黃"
            android:textColor="#000000" />

        <TextView
            android:id="@+id/tv_two"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1.0"
            android:gravity="center"
            android:text="淡黃"
            android:textColor="#000000" />

        <TextView
            android:id="@+id/tv_three"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1.0"
            android:gravity="center"
            android:text="淺棕"
            android:textColor="#000000" />
    </LinearLayout>

    <ImageView
        android:id="@+id/img_cursor"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:scaleType="matrix"
        android:src="@mipmap/line" />

    <android.support.v4.view.ViewPager
        android:id="@+id/vpager_four"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_gravity="center"
        android:layout_weight="1.0"
        android:flipInterval="30"
        android:persistentDrawingCache="animation" />

</LinearLayout> 
接著到我們的Activity了,我們來捋下思路:

Step 1:我們需要讓我們的移動塊在第一個文字下居中,那這裡就要算一下偏移量: 先獲得圖片寬度pw,然後獲取螢幕寬度sw,計算方法很簡單:
offset(偏移量) = ((sw / 3)-pw) / 2 //螢幕寬/3 - 圖片寬度,然後再除以2,左右嘛!
然後我麼你呼叫setImageMatrix設定滑塊當前的位置:
同時我們也把切換一頁和兩頁,滑塊的移動距離也算出來,很簡單:
one = offset * 2 + pw;
two = one * 2;

Step 2:當我們滑動頁面時,我們的滑塊要進行移動,我們要為ViewPager新增一個 OnPageChangeListener事件,我們需要對滑動後的頁面來做一個判斷,同時記錄滑動前處於 哪個頁面
FourActvitiy.java:

/**
 * Created by Jay on 2015/10/8 0008.
 */
public class FourActivity extends AppCompatActivity implements View.OnClickListener,
        ViewPager.OnPageChangeListener {

    private ViewPager vpager_four;
    private ImageView img_cursor;
    private TextView tv_one;
    private TextView tv_two;
    private TextView tv_three;

    private ArrayList<View> listViews;
    private int offset = 0;//移動條圖片的偏移量
    private int currIndex = 0;//當前頁面的編號
    private int bmpWidth;// 移動條圖片的長度
    private int one = 0; //移動條滑動一頁的距離
    private int two = 0; //滑動條移動兩頁的距離

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_four);
        initViews();
    }


    private void initViews() {
        vpager_four = (ViewPager) findViewById(R.id.vpager_four);
        tv_one = (TextView) findViewById(R.id.tv_one);
        tv_two = (TextView) findViewById(R.id.tv_two);
        tv_three = (TextView) findViewById(R.id.tv_three);
        img_cursor = (ImageView) findViewById(R.id.img_cursor);

        //下劃線動畫的相關設定:
        bmpWidth = BitmapFactory.decodeResource(getResources(), R.mipmap.line).getWidth();// 獲取圖片寬度
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenW = dm.widthPixels;// 獲取解析度寬度
        offset = (screenW / 3 - bmpWidth) / 2;// 計算偏移量
        Matrix matrix = new Matrix();
        matrix.postTranslate(offset, 0);
        img_cursor.setImageMatrix(matrix);// 設定動畫初始位置
        //移動的距離
        one = offset * 2 + bmpWidth;// 移動一頁的偏移量,比如1->2,或者2->3
        two = one * 2;// 移動兩頁的偏移量,比如1直接跳3


        //往ViewPager填充View,同時設定點選事件與頁面切換事件
        listViews = new ArrayList<View>();
        LayoutInflater mInflater = getLayoutInflater();
        listViews.add(mInflater.inflate(R.layout.view_one, null, false));
        listViews.add(mInflater.inflate(R.layout.view_two, null, false));
        listViews.add(mInflater.inflate(R.layout.view_three, null, false));
        vpager_four.setAdapter(new MyPagerAdapter(listViews));
        vpager_four.setCurrentItem(0);          //設定ViewPager當前頁,從0開始算

        tv_one.setOnClickListener(this);
        tv_two.setOnClickListener(this);
        tv_three.setOnClickListener(this);

        vpager_four.addOnPageChangeListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_one:
                vpager_four.setCurrentItem(0);
                break;
            case R.id.tv_two:
                vpager_four.setCurrentItem(1);
                break;
            case R.id.tv_three:
                vpager_four.setCurrentItem(2);
                break;
        }
    }

    @Override
    public void onPageSelected(int index) {
        Animation animation = null;
        switch (index) {
            case 0:
                if (currIndex == 1) {
                    animation = new TranslateAnimation(one, 0, 0, 0);
                } else if (currIndex == 2) {
                    animation = new TranslateAnimation(two, 0, 0, 0);
                }
                break;
            case 1:
                if (currIndex == 0) {
                    animation = new TranslateAnimation(offset, one, 0, 0);
                } else if (currIndex == 2) {
                    animation = new TranslateAnimation(two, one, 0, 0);
                }
                break;
            case 2:
                if (currIndex == 0) {
                    animation = new TranslateAnimation(offset, two, 0, 0);
                } else if (currIndex == 1) {
                    animation = new TranslateAnimation(one, two, 0, 0);
                }
                break;
        }
        currIndex = index;
        animation.setFillAfter(true);// true表示圖片停在動畫結束位置
        animation.setDuration(300); //設定動畫時間為300毫秒
        img_cursor.startAnimation(animation);//開始動畫
    }

    @Override
    public void onPageScrollStateChanged(int i) {

    }

    @Override
    public void onPageScrolled(int i, float v, int i1) {

    }
}