ViewPager創(chuàng)建步驟詳解

ViewPager創(chuàng)建步驟詳解

Android


ViewPager是android擴(kuò)展包v4包中的類,這個(gè)類可以讓用戶左右切換當(dāng)前的view。
在應(yīng)用第一次啟動(dòng)時(shí),經(jīng)常會(huì)看到用ViewPager實(shí)現(xiàn)的Splash頁面。

我們首先來看看API對(duì)于這個(gè)類的表述:

Layout manager that allows the user to flip left and right through pages of data. You supply an implementation of a PagerAdapter to generate the pages that the view shows.
Note this class is currently under early design and development. The API will likely change in later updates of the compatibility library, requiring changes to the source code of apps when they are compiled against the newer version.
ViewPager is most often used in conjunction with Fragment, which is a convenient way to supply and manage the lifecycle of each page. There are standard adapters implemented for using fragments with the ViewPager, which cover the most common use cases. These are FragmentPagerAdapter andFragmentStatePagerAdapter; each of these classes have simple code showing how to build a full user interface with them.

從這個(gè)描述中我們知道幾點(diǎn):

1)ViewPager類直接繼承了ViewGroup類,所有它是一個(gè)容器類,可以在其中添加其他的view類。

2)ViewPager類需要一個(gè)PagerAdapter適配器類給它提供數(shù)據(jù)。

3)ViewPager經(jīng)常和Fragment一起使用,并且提供了專門的FragmentPagerAdapter和FragmentStatePagerAdapter類供Fragment中的ViewPager使用。


好了,下面我們來實(shí)現(xiàn)Splash頁面吧!

步驟一:

創(chuàng)建一個(gè)Activity,并在布局文件中添加ViewPager組件:

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

步驟二:

新建一個(gè)類并集成PagerAdapter,即構(gòu)建適配器

public class GuideAdapter extends PagerAdapter {
    //圖片資源合集:ViewPager滾動(dòng)的頁面種類
    private int[] mImageId = new int[]{R.drawable.guide_1, R.drawable.guide_2, R.drawable.guide_3};
    private Context mContext;
 
    public int[] getImageId() {
        return mImageId;
    }
    //構(gòu)造函數(shù)
    public GuideAdapter(Context context) {
        super();
        this.mContext = context;
    }
    //返回填充ViewPager頁面的數(shù)量
    @Override
    public int getCount() {
        return mImageId.length;
    }
    //銷毀ViewPager內(nèi)某個(gè)頁面時(shí)調(diào)用
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

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

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        ImageView imageView = new ImageView(mContext);
        //設(shè)置背景資源
        imageView.setBackgroundResource(mImageId[position]);
        container.addView(imageView);
        return imageView;
    }
}

步驟三:

在Acyivityy的Oncreate();內(nèi)獲取ViewPager控件,并設(shè)置適配器:

//獲取適配器
GuideAdapter mGuideAdapter = new GuideAdapter(getApplicationContext());
//獲取ViewPager控件
ViewPager mGuideVp = (ViewPager)findViewById(R.id.vp_guide_guide);
//設(shè)置適配器
mGuideVp.setAdapter(mGuideAdapter);

大功告成!
下面就是設(shè)置ViewPager上面的小紅點(diǎn)指示器:

步驟一:

首先,在res/drawable文件內(nèi)新建兩個(gè)xml文件,分別是shape_point_gray.xmlshape_point_red.xml,代表指示器的兩種狀態(tài):

  • shape_point_gray.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

    <size
        android:width="8dp"
        android:height="8dp"/>
    <solid
        android:color="@android:color/darker_gray"/>

</shape>
  • shape_point_red.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="oval">

    <size
        android:width="8dp"
        android:height="8dp"/>
    <solid
        android:color="@android:color/holo_red_light"/>

</shape>

步驟二:

先設(shè)置灰色狀態(tài)的圓點(diǎn):在Activity的Oncreate();內(nèi)添加以下代碼:

//初始化灰色小圓點(diǎn)
        for (int i=0; i<mGuideAdapter.getImageId().length; i++){
            ImageView point = new ImageView(this);
            point.setBackgroundResource(R.drawable.shape_point_gray);
            LinearLayout.LayoutParams params = 
            new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            if (i > 0){
                params.leftMargin = 10;//設(shè)置左邊距
            }
            point.setLayoutParams(params);
            mLinLayGuidepointContainer.addView(point);
        }

步驟三:

設(shè)置紅色狀態(tài)的圓點(diǎn):在布局文件內(nèi)添加以下代碼:

<RelativeLayout
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="50dp"
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <LinearLayout
            android:id="@+id/linLay_guide_pointContainer"
            android:orientation="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
        <ImageView
            android:id="@+id/iv_guide_redPoint"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/shape_point_red"/>
</RelativeLayout>

步驟四:

此時(shí)已經(jīng)完成了紅點(diǎn)和灰點(diǎn)的初始化工作,下面就是當(dāng)ViewPager頁面左右滑動(dòng)時(shí),紅點(diǎn)的位置跟著變化,實(shí)現(xiàn)指示器功能:

在步驟二時(shí)已經(jīng)在頁面添加了水平居中的三個(gè)灰色的圓點(diǎn),下面就是獲取相鄰兩個(gè)灰點(diǎn)之間的距離:

可以通過監(jiān)聽Layout執(zhí)行結(jié)束事件來獲取,代碼如下:

int mPointWidth;
ImageView mIvGuideRedPoint = (ImageView)findViewById(R.id.iv_guide_redPoint);
// meaure->layout->draw(必須在onCreate執(zhí)行結(jié)束之后才開始繪制),
        // 所以不能直接在onCreate中獲取位置相關(guān)信息
        // 監(jiān)聽layout執(zhí)行結(jié)束事件, 結(jié)束之后再去獲取位置信息,計(jì)算圓點(diǎn)間距
        // 獲取視圖樹,hierarchyviewer.bat
        mIvGuideRedPoint.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {

                    // layout方法執(zhí)行結(jié)束之后,回調(diào)此方法
                    @Override
                    public void onGlobalLayout() {
                        mPointWidth = mLinLayGuidepointContainer
                        .getChildAt(1)
                        .getLeft() -
                                mLinLayGuidepointContainer
                                .getChildAt(0)
                                .getLeft();
                    }
                });

然后通過ViewPager的頁面監(jiān)聽事件來更改紅點(diǎn)的狀態(tài):

//頁面滑動(dòng)事件
        mGuideVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            // 頁面滑動(dòng)過程中回調(diào)
            @Override
            public void onPageScrolled(int position, float positionOffset,
                                       int positionOffsetPixels) {
                int leftMargin = (int) 
                (mPointWidth * positionOffset + mPointWidth * position);
                //重新修改布局參數(shù)
                RelativeLayout.LayoutParams params =
                        (RelativeLayout.LayoutParams)  mIvGuideRedPoint.getLayoutParams();
                params.leftMargin = leftMargin;
                mIvGuideRedPoint.setLayoutParams(params);
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

ok!終于完成了,好好試下!有耐心才可成功
效果圖(按鈕沒有實(shí)現(xiàn)):

ViewPager效果圖.gif
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容