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

ViewPager 打造應用引導頁:圖文代碼完整實戰

編輯:關於 Android 開發

用 ViewPager 實現應用引導界面

下面要實現的是這樣一種引導頁效果:引用時先播放一段圖片動畫,動畫結束後進入引導頁面。

頁面下方的小圖片,點擊時會讓 ViewPager 消失,再點一次又顯示出來。

先看開屏頁——其中的動畫設計還是頗有借鑒價值的。

package com.demo.activity;
import com.demo.pullrefresh.R;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.widget.RelativeLayout;
/**
 * 閃屏頁
 */
public class SplashActivity extends Activity {
    private RelativeLayout rl_root;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splashactivity);
        rl_root = (RelativeLayout) findViewById(R.id.rl_root);
        startAnim();
    }
    /** 開啟動畫 */
    private void startAnim() {
        // 動畫集合
        AnimationSet set = new AnimationSet(false);
        // 旋轉動畫
        RotateAnimation rotate = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        rotate.setDuration(1000);
        rotate.setFillAfter(true);
        // 縮放動畫
        ScaleAnimation scale = new ScaleAnimation(0, 1, 0, 1, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        scale.setDuration(1000);
        scale.setFillAfter(true);
        // 漸變動畫
        AlphaAnimation alpha = new AlphaAnimation(0, 1);
        alpha.setDuration(2000);
        alpha.setFillAfter(true);
        set.addAnimation(rotate);
        set.addAnimation(scale);
        set.addAnimation(alpha);
        // 動畫監聽
        set.setAnimationListener(new AnimationListener() {
            @Override
            public void onAnimationStart(Animation arg0) { }
            @Override
            public void onAnimationRepeat(Animation arg0) { }
            // 動畫執行完
            @Override
            public void onAnimationEnd(Animation arg0) {
                startActivity(new Intent(SplashActivity.this, GuideActivity.class));
                finish();
            }
        });
        rl_root.startAnimation(set);
    }
    /** 跳轉到下個界面 */
    private void jumpNextPage() {
        SharedPreferences sPreferences = getSharedPreferences("infos", MODE_PRIVATE);
        boolean isuserGuid = sPreferences.getBoolean("key", false);
        if (!isuserGuid) {
            startActivity(new Intent(SplashActivity.this, GuideActivity.class));
        } else {
            startActivity(new Intent(SplashActivity.this, MainActivity.class));
        }
        finish();
    }
}

再來看引導界面:

package com.demo.activity;
import java.util.ArrayList;
import com.demo.pullrefresh.R;
import android.app.Activity;
import android.content.Intent;
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.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
public class GuideActivity extends Activity {
    /** 圖片數據 */
    private static final int[] mImageIds = new int[] {
        R.drawable.guide_1, R.drawable.guide_2, R.drawable.guide_3
    };
    private ArrayList mImageViewList;
    private ViewPager vPager;
    private LinearLayout llPointGroup;   // 引導原點的父控件
    private View viewRedPoint;           // 小紅點
    private int mPointWidth;             // 圓點間的距離
    private Button btnStart;             // 進入其他界面
    private ImageView igv_image;
    private RelativeLayout rl_one;
    private boolean visibility_flag;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_guide);
        vPager = (ViewPager) findViewById(R.id.vp_guide);
        llPointGroup = (LinearLayout) findViewById(R.id.ll_point_group);
        viewRedPoint = findViewById(R.id.view_red_position);
        btnStart = (Button) findViewById(R.id.btn_start);
        igv_image = (ImageView) findViewById(R.id.igv_image);
        rl_one = (RelativeLayout) findViewById(R.id.rl_one);
        initViews();
        vPager.setAdapter(new GuideAdapter());
        vPager.setOnPageChangeListener(new GuidePageListener());
        igv_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (visibility_flag) {
                    rl_one.setVisibility(View.VISIBLE);
                    visibility_flag = false;
                } else {
                    rl_one.setVisibility(View.INVISIBLE);
                    visibility_flag = true;
                }
            }
        });
        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                startActivity(new Intent(GuideActivity.this, MainProducte.class));
                finish();
            }
        });
    }
    /** 初始化界面 */
    private void initViews() {
        mImageViewList = new ArrayList();
        // 初始化引導的 3 個界面
        for (int i = 0; i < mImageIds.length; i++) {
            ImageView imageView = new ImageView(this);
            imageView.setBackgroundResource(mImageIds[i]);
            mImageViewList.add(imageView);
        }
        // 初始化引導頁的小圓點
        for (int i = 0; i < mImageIds.length; i++) {
            View pointView = new View(this);
            pointView.setBackgroundResource(R.drawable.shape_point_gray);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(10, 10);
            if (i > 0) {
                params.leftMargin = 10;  // 設置圓點間隔
            }
            pointView.setLayoutParams(params);
            llPointGroup.addView(pointView);
        }
        // 獲取視圖樹,對 layout 結束事件進行監聽
        llPointGroup.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                llPointGroup.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                mPointWidth = llPointGroup.getChildAt(1).getLeft() - llPointGroup.getChildAt(0).getLeft();
                System.out.println("圓點距離:" + mPointWidth);
            }
        });
    }
    /** ViewPager 數據的適配器 */
    class GuideAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return mImageIds.length;
        }
        // 判斷是否由對象生成界面
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
        // 初始化 position 位置的界面
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(mImageViewList.get(position));
            return mImageViewList.get(position);
        }
        // 摧毀 position 位置的界面
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }
    /** ViewPager 的滑動監聽 */
    class GuidePageListener implements OnPageChangeListener {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            System.out.println("當前位置:" + position + ";百分比:" + positionOffset + "; 移動距離:" + positionOffsetPixels);
            int len = (int) (mPointWidth * positionOffset + position * mPointWidth);
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewRedPoint.getLayoutParams();
            params.leftMargin = len;
            viewRedPoint.setLayoutParams(params);
        }
        // 某個頁面被選中
        @Override
        public void onPageSelected(int position) {
            if (position == mImageIds.length - 1) {  // 最後一個頁面
                btnStart.setVisibility(View.VISIBLE);
            } else {
                btnStart.setVisibility(View.INVISIBLE);
            }
        }
        @Override
        public void onPageScrollStateChanged(int state) { }
    }
}

效果演示:

activity_guide.xml 布局:

<?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" >
    <RelativeLayout android:id="@+id/rl_one"
        android:layout_width="match_parent"
        android:layout_height="400dp" >
        <android.support.v4.view.ViewPager
            android:id="@+id/vp_guide"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
        <Button android:id="@+id/btn_start"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="50dp"
            android:background="@drawable/btn_guide_selector"
            android:padding="5dp"
            android:visibility="invisible"
            android:text="下個"
            android:textColor="@drawable/btn_guide_text_selector" />
        <RelativeLayout android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="15dp" >
            <LinearLayout android:id="@+id/ll_point_group"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal" >
            </LinearLayout>
            <View android:id="@+id/view_red_position"
                android:layout_width="8dp"
                android:layout_height="8dp"
                android:background="@drawable/shape_point_red" />
        </RelativeLayout>
    </RelativeLayout>
    <RelativeLayout android:layout_below="@id/rl_one"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#eee">
        <ImageView android:id="@+id/igv_image"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:src="@drawable/ic_launcher"
            android:layout_centerInParent="true" />
    </RelativeLayout>
</RelativeLayout>

btn_guide_text_selector.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android" >
    <item android:state_pressed="true" android:color="@android:color/black"></item>
    <item android:color="@android:color/white"/>
</selector>

另外演示一下帶切換效果的 GIF:

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