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

App 引導頁這樣做:ViewPager 實戰教學

編輯:關於 Android 開發

安裝完 App 第一次打開時看到的那幾頁滑動式介紹,幾乎都是用 ViewPager 做的。它看起來像一個橫向可滑動的容器,理解之後會發現用法和 ListView 有不少相似之處:都需要 Adapter,都需要監聽使用者操作。本文從零開始實作一個完整的引導頁,並處理「只顯示一次」這個實際需求。

先建立基本認知

在 ADT 時代的專案中,ViewPager 來自 android.support.v4.view.ViewPager 這個套件。你可以把它想像成一個 ListView,只不過滑動方向是橫向的。

ListView 需要 Adapter,ViewPager 也需要;ListView 要監聽項目點擊,ViewPager 則要監聽頁面切換。掌握了這個類比,剩下的就很直觀了。

第一步:在版面中宣告 ViewPager

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
</RelativeLayout>

接著在 Java 中 findViewById 取得它,避免後續空指標問題。

第二步:準備每一頁的版面

ViewPager 本質上是一個 View 的容器,所以我們得先準備好要放進去的 View。以最後一頁為例,通常會擺一個「進入」按鈕:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@drawable/guide_3" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:gravity="center_horizontal"
        android:orientation="horizontal">

        <Button
            android:id="@+id/start_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="進入" />
    </LinearLayout>
</RelativeLayout>

第三步:撰寫 Adapter

這裡有個容易搞錯的點:Adapter 必須繼承 PagerAdapter,而不是一般 List 用的 BaseAdapter。

package com.mark.viewpagerdemo;

import java.util.List;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;

public class ViewPageAdapter extends PagerAdapter {

    private List<View> views;
    private Context context;

    public ViewPageAdapter(List<View> mViews, Context mContext) {
        this.context = mContext;
        this.views = mViews;
    }

    /** 銷毀已經滑出畫面的頁面,及時釋放資源 */
    @Override
    public void destroyItem(View container, int position, Object object) {
        ((ViewPager) container).removeView(views.get(position));
    }

    /** 這個方法的角色,相當於 ListView Adapter 的 getView */
    @Override
    public Object instantiateItem(View container, int position) {
        ((ViewPager) container).addView(views.get(position));
        return views.get(position);
    }

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

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

其中 instantiateItem() 就是整個 Adapter 的核心:把指定位置的 View 加入容器並回傳。如果你只是要單純的圖片輪播、不需要額外效果,寫到這裡其實已經可以跑了。

第四步:加上頁面指示點

所謂「效果」,通常指的就是底部那排小圓點:目前所在頁是亮點,其餘是暗點。它能讓使用者知道自己在第幾頁,視覺上也更完整。

實作方式是在 ViewPager 所在的版面中擺幾個 ImageView,然後在 OnPageChangeListener 的 onPageSelected() 裡切換圖片資源。注意:指示點只需要加在承載 ViewPager 的那個版面,不需要每個子頁面都放。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

    <LinearLayout
        android:id="@+id/ll"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:gravity="center_horizontal"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/iv1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/login_point_selected" />

        <ImageView
            android:id="@+id/iv2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/login_point" />

        <ImageView
            android:id="@+id/iv3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/login_point" />
    </LinearLayout>
</RelativeLayout>
package com.mark.viewpagerdemo;

import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class Guide extends Activity implements OnPageChangeListener {

    private ViewPager vp;
    private ViewPageAdapter vpAdapter;
    private List<View> views;
    private ImageView[] dots;
    int[] ids = new int[] { R.id.iv1, R.id.iv2, R.id.iv3 };
    private Button enter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.guide);
        initViews();
        initDots();
    }

    public void initViews() {
        views = new ArrayList<View>();
        LayoutInflater inflater = LayoutInflater.from(this);
        views.add(inflater.inflate(R.layout.one, null));
        views.add(inflater.inflate(R.layout.two, null));
        views.add(inflater.inflate(R.layout.three, null));

        // 按鈕位於第三個 view 中,必須先取得該 view 才能 findViewById
        enter = (Button) views.get(2).findViewById(R.id.start_btn);
        enter.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(Guide.this, MainActivity.class));
                finish();
            }
        });

        vp = (ViewPager) findViewById(R.id.viewpager);
        vpAdapter = new ViewPageAdapter(views, this);
        vp.setAdapter(vpAdapter);
        vp.setOnPageChangeListener(this);
    }

    public void initDots() {
        dots = new ImageView[views.size()];
        for (int i = 0; i < dots.length; i++) {
            dots[i] = (ImageView) findViewById(ids[i]);
        }
    }

    @Override
    public void onPageScrollStateChanged(int arg0) { }

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

    @Override
    public void onPageSelected(int arg0) {
        for (int i = 0; i < ids.length; i++) {
            if (arg0 == i) {
                dots[i].setImageResource(R.drawable.login_point_selected);
            } else {
                dots[i].setImageResource(R.drawable.login_point);
            }
        }
    }
}

有一個細節值得注意:enter 按鈕在第三個 view 裡,而我們是在 Guide Activity 中查找它,所以必須先 views.get(2) 拿到該 view,再呼叫它的 findViewById()。直接在 Activity 上找是找不到的。

第五步:只顯示一次

做到這裡功能上已經完整,但還有個問題:每次開 App 都會看到引導頁,顯然不合理。真正的需求是「第一次才顯示」。

思路是用 SharedPreferences 記錄一個旗標。同時我們需要一個中間層的啟動頁:App 打開時先停在這裡,判斷完再決定要跳去引導頁還是主頁。

版面很簡單,一張歡迎圖:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@drawable/welcome_android" />
</LinearLayout>
package com.mark.viewpagerdemo;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;

public class Welcome extends Activity {

    private static final int TIME = 2000;      // 等待時間
    private static final int GO_HOME = 1000;
    private static final int GO_GUIDE = 1001;

    private boolean isFirstIn = true;

    private void initValue() {
        SharedPreferences sp = getSharedPreferences("ViewPagerDemo", MODE_PRIVATE);
        isFirstIn = sp.getBoolean("isFirstIn", true);
        if (isFirstIn) {
            mHandler.sendEmptyMessageDelayed(GO_GUIDE, TIME);
            Editor editor = sp.edit();
            editor.putBoolean("isFirstIn", false);
            editor.commit();
        } else {
            mHandler.sendEmptyMessageDelayed(GO_HOME, TIME);
        }
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case GO_HOME:
                    goHome();
                    break;
                case GO_GUIDE:
                    goGuide();
                    break;
            }
        }
    };

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

    private void goHome() {
        startActivity(new Intent(Welcome.this, MainActivity.class));
        finish();
    }

    private void goGuide() {
        startActivity(new Intent(Welcome.this, Guide.class));
        finish();
    }
}

這裡有兩個設計理由值得說明。第一,等待時間不能直接用 Thread.sleep() 在主執行緒中實作,那會造成 ANR,所以用 Handler 送出延遲訊息;第二,UI 更新必須在主執行緒進行,因此 msg.what 的分派也放在主執行緒的 Handler 中處理。

如果想让寫法更乾淨,也可以把旗標的初始化移到 Application 或靜態區塊中,讓判斷在更早的時機完成。

測試與回顧

跑起來之後會發現,只有第一次安裝後開啟才會看到引導頁,進入過主頁之後就不再出現——除非你清除資料或重新安裝。

這個小專案涵蓋的知識點:

  • 理解 ViewPager 的定位與基本用法
  • 學會撰寫 PagerAdapter,特別是 instantiateItem() 與 destroyItem() 的分工
  • 掌握 OnPageChangeListener 中三個回呼各自的時機
  • 用 Handler 搭配延遲訊息完成跳轉,並遵守主執行緒更新 UI 的原則
  • 用 SharedPreferences 記錄狀態,實作出「一次性引導」的效果

介面醜不醜是另一回事,核心思路都在這裡了。實際專案中可以再往兩個方向延伸:一是用 ViewPager.setPageTransformer() 加入滑動時的縮放或視差效果;二是把指示點改成 Shape drawable 或第三方庫,讓樣式更精緻。

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