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

Android 引導頁實作:ViewPager 圖片滑動與底部小圓點指示器

編輯:Android 程式設計入門

本篇說明如何製作常見的啟動引導頁(Guide Page):可左右滑動的圖片,加上會跟著換色的底部小圓點,並附一個「跳過」按鈕直接進入主畫面。圖片與小圓點的素材可自行準備。

版面配置

用 FrameLayout 疊兩層:底層是 ViewPager 負責滑動,上層是 RelativeLayout 放小圓點與跳過按鈕。

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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:background="@android:color/holo_blue_dark"
    tools:context=".MainActivity" >

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

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <LinearLayout
            android:id="@+id/viewGroup"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_marginBottom="30dp"
            android:gravity="center_horizontal"
            android:orientation="horizontal" >
        </LinearLayout>

        <TextView
            android:id="@+id/guideBotton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:layout_alignParentBottom="true"
            android:layout_margin="10dp"
            android:layout_marginBottom="96dp"
            android:text="跳過 >>>"
            android:textColor="#D9D919"
            android:textSize="17dp" />
    </RelativeLayout>
</FrameLayout>

程式碼

package net.oschina.app;

// 底部小圓點會隨頁面變化的引導頁
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class Guide extends Activity implements OnPageChangeListener, View.OnTouchListener {
    private ViewPager mViewPager = null;
    private LinearLayout mViewGroup = null;
    private TextView textView;
    private int[] mImageIds = {R.drawable.guide1, R.drawable.guide2,
            R.drawable.guide3, R.drawable.guide4};
    private ImageView[] mImageViews = null;
    private ImageView[] mTips = null;

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

        textView = (TextView) findViewById(R.id.guideBotton);
        Buttonlistenner buttonlistenner = new Buttonlistenner();
        textView.setOnClickListener(buttonlistenner);
        textView.setClickable(true);

        mViewGroup = (LinearLayout) findViewById(R.id.viewGroup);
        mViewPager = (ViewPager) findViewById(R.id.viewPager);

        // 建立底部小圓點,第一頁用亮色,其餘用暗色
        mTips = new ImageView[mImageIds.length];
        for (int i = 0; i < mTips.length; i++) {
            ImageView iv = new ImageView(this);
            iv.setLayoutParams(new LayoutParams(40, 40));
            mTips[i] = iv;
            if (i == 0) {
                iv.setBackgroundResource(R.drawable.white_dot);
            } else {
                iv.setBackgroundResource(R.drawable.dark_dot);
            }
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            lp.leftMargin = 40;
            lp.rightMargin = 40;
            mViewGroup.addView(iv, lp);
        }

        // 建立每一頁的圖片,並先做降採樣避免記憶體浪費
        mImageViews = new ImageView[mImageIds.length];
        int reqWidth = getWindowManager().getDefaultDisplay().getWidth();
        int reqHeight = getWindowManager().getDefaultDisplay().getHeight();
        for (int i = 0; i < mImageViews.length; i++) {
            ImageView iv = new ImageView(this);
            mImageViews[i] = iv;
            iv.setImageBitmap(decodeSampledBitmapFromResource(
                    getResources(), mImageIds[i], reqWidth, reqHeight));
            iv.setScaleType(ImageView.ScaleType.FIT_XY);
        }

        mViewPager.setAdapter(new MyPagerAdapter());
        mViewPager.setOnPageChangeListener(this);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        v.getParent().requestDisallowInterceptTouchEvent(true);
        return false;
    }

    class MyPagerAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return mImageIds.length;
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(mImageViews[position]);
            return mImageViews[position];
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(mImageViews[position]);
        }
    }

    // 換頁時同步切換小圓點的顏色
    @Override
    public void onPageSelected(int position) {
        for (int i = 0; i < mTips.length; i++) {
            if (position == i) {
                mTips[i].setBackgroundResource(R.drawable.white_dot);
            } else {
                mTips[i].setBackgroundResource(R.drawable.dark_dot);
            }
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }

    @Override
    public void onPageScrolled(int position, float offset, int offsetPixels) {
        mViewPager.getParent().requestDisallowInterceptTouchEvent(true);
    }

    /** 先量尺寸,再依螢幕大小降採樣解碼,避免大圖造成 OOM */
    private static Bitmap decodeSampledBitmapFromResource(Resources res,
                                                          int resId, int reqWidth, int reqHeight) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, opts);
        int inSampleSize = cacluateInSampledSize(opts, reqWidth, reqHeight);
        opts.inSampleSize = inSampleSize;
        opts.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res, resId, opts);
    }

    private static int cacluateInSampledSize(BitmapFactory.Options opts, int width, int height) {
        if (opts == null) {
            return 1;
        }
        int inSampleSize = 1;
        int realWidth = opts.outWidth;
        int realHeight = opts.outHeight;
        if (realWidth > width || realHeight > height) {
            int heightRatio = realHeight / height;
            int widthRatio = realWidth / width;
            inSampleSize = (widthRatio > heightRatio) ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }

    class Buttonlistenner implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setClass(Guide.this, MainActivity.class);
            startActivity(intent);
            finish();
        }
    }
}

兩個關鍵細節

① 記得 finish()

跳轉時一定要把引導頁結束掉:

startActivity(intent);
finish();

否則使用者每按一次返回鍵都會被送回引導頁,而且引導頁會一直留在堆疊中佔用記憶體。頁面越多,這個問題越明顯。

② destroyItem() 要真的移除檢視

PagerAdapter 的 destroyItem() 若不實作移除,滑走的頁面不會被回收,記憶體會隨頁面數量線性成長。這一步很容易在抄範例時被省略,卻是長流程引導頁能否穩定運行的關鍵。

③ 引導頁只該出現一次

實務上通常會用 SharedPreferences 記一個「已看過引導頁」的標記,在啟動頁判斷:第一次安裝才跳 Guide,之後直接進主畫面。否則每次開 App 都得滑過好幾頁,使用者很快就會反感。

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