Andoird 自定義ViewGroup實現豎向引導界面

轉載請表明出處:http://write.blog.csdn.net/postedit/23692439

一般進入APP都有歡迎界面,基本都是水平滾動的,今天和大家分享一個垂直滾動的例子。

先來看看效果把:



1、首先是佈局文件:

[html] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. <com.example.verticallinearlayout.VerticalLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:id="@+id/id_main_ly"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="fill_parent"  
  6.     android:orientation="vertical"  
  7.     android:background="#fff" >  
  8.   
  9.     <RelativeLayout  
  10.         android:layout_width="fill_parent"  
  11.         android:layout_height="fill_parent"  
  12.         android:background="@drawable/w02" >  
  13.   
  14.         <Button  
  15.             android:layout_width="wrap_content"  
  16.             android:layout_height="wrap_content"  
  17.             android:text="hello" />  
  18.     </RelativeLayout>  
  19.   
  20.     <RelativeLayout  
  21.         android:layout_width="fill_parent"  
  22.         android:layout_height="fill_parent"  
  23.         android:background="@drawable/w03" >  
  24.   
  25.         <Button  
  26.             android:layout_width="wrap_content"  
  27.             android:layout_height="wrap_content"  
  28.             android:layout_centerInParent="true"  
  29.             android:background="#fff"  
  30.             android:text="hello" />  
  31.     </RelativeLayout>  
  32.   
  33.     <RelativeLayout  
  34.         android:layout_width="fill_parent"  
  35.         android:layout_height="fill_parent"  
  36.         android:background="@drawable/w04" >  
  37.   
  38.         <Button  
  39.             android:layout_width="wrap_content"  
  40.             android:layout_height="wrap_content"  
  41.             android:layout_centerInParent="true"  
  42.             android:text="hello" />  
  43.     </RelativeLayout>  
  44.   
  45.     <RelativeLayout  
  46.         android:layout_width="fill_parent"  
  47.         android:layout_height="fill_parent"  
  48.         android:background="@drawable/w05" >  
  49.   
  50.         <Button  
  51.             android:layout_width="wrap_content"  
  52.             android:layout_height="wrap_content"  
  53.             android:layout_centerInParent="true"  
  54.             android:text="hello" />  
  55.     </RelativeLayout>  
  56.   
  57. </com.example.verticallinearlayout.VerticalLinearLayout>  
在自定義的ViewGroup中放入了4個RelativeLayout,每個RelativeLayout都設置了背景圖片,背景圖片來自微信~

2、主要看自定義的Layout了

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. package com.example.verticallinearlayout;  
  2.   
  3. import android.content.Context;  
  4. import android.util.AttributeSet;  
  5. import android.util.DisplayMetrics;  
  6. import android.util.Log;  
  7. import android.view.MotionEvent;  
  8. import android.view.VelocityTracker;  
  9. import android.view.View;  
  10. import android.view.ViewGroup;  
  11. import android.view.WindowManager;  
  12. import android.widget.Scroller;  
  13.   
  14. public class VerticalLinearLayout extends ViewGroup  
  15. {  
  16.     /** 
  17.      * 屏幕的高度 
  18.      */  
  19.     private int mScreenHeight;  
  20.     /** 
  21.      * 手指按下時的getScrollY 
  22.      */  
  23.     private int mScrollStart;  
  24.     /** 
  25.      * 手指擡起時的getScrollY 
  26.      */  
  27.     private int mScrollEnd;  
  28.     /** 
  29.      * 記錄移動時的Y 
  30.      */  
  31.     private int mLastY;  
  32.     /** 
  33.      * 滾動的輔助類 
  34.      */  
  35.     private Scroller mScroller;  
  36.     /** 
  37.      * 是否正在滾動 
  38.      */  
  39.     private boolean isScrolling;  
  40.     /** 
  41.      * 加速度檢測 
  42.      */  
  43.     private VelocityTracker mVelocityTracker;  
  44.     /** 
  45.      * 記錄當前頁 
  46.      */  
  47.     private int currentPage = 0;  
  48.   
  49.     private OnPageChangeListener mOnPageChangeListener;  
  50.   
  51.     public VerticalLinearLayout(Context context, AttributeSet attrs)  
  52.     {  
  53.         super(context, attrs);  
  54.   
  55.         /** 
  56.          * 獲得屏幕的高度 
  57.          */  
  58.         WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);  
  59.         DisplayMetrics outMetrics = new DisplayMetrics();  
  60.         wm.getDefaultDisplay().getMetrics(outMetrics);  
  61.         mScreenHeight = outMetrics.heightPixels;  
  62.         // 初始化  
  63.         mScroller = new Scroller(context);  
  64.     }  
  65.   
  66.     @Override  
  67.     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)  
  68.     {  
  69.         super.onMeasure(widthMeasureSpec, heightMeasureSpec);  
  70.         int count = getChildCount();  
  71.         for (int i = 0; i < count; ++i)  
  72.         {  
  73.             View childView = getChildAt(i);  
  74.             measureChild(childView, widthMeasureSpec,mScreenHeight);  
  75.         }  
  76.     }  
  77.   
  78.     @Override  
  79.     protected void onLayout(boolean changed, int l, int t, int r, int b)  
  80.     {  
  81.         if (changed)  
  82.         {  
  83.             int childCount = getChildCount();  
  84.             // 設置主佈局的高度  
  85.             MarginLayoutParams lp = (MarginLayoutParams) getLayoutParams();  
  86.             lp.height = mScreenHeight * childCount;  
  87.             setLayoutParams(lp);  
  88.   
  89.             for (int i = 0; i < childCount; i++)  
  90.             {  
  91.                 View child = getChildAt(i);  
  92.                 if (child.getVisibility() != View.GONE)  
  93.                 {  
  94.                     child.layout(l, i * mScreenHeight, r, (i + 1) * mScreenHeight);// 調用每個自佈局的layout  
  95.                 }  
  96.             }  
  97.   
  98.         }  
  99.   
  100.     }  
  101.   
  102.     @Override  
  103.     public boolean onTouchEvent(MotionEvent event)  
  104.     {  
  105.         // 如果當前正在滾動,調用父類的onTouchEvent  
  106.         if (isScrolling)  
  107.             return super.onTouchEvent(event);  
  108.   
  109.         int action = event.getAction();  
  110.         int y = (int) event.getY();  
  111.   
  112.         obtainVelocity(event);  
  113.         switch (action)  
  114.         {  
  115.         case MotionEvent.ACTION_DOWN:  
  116.   
  117.             mScrollStart = getScrollY();  
  118.             mLastY = y;  
  119.             break;  
  120.         case MotionEvent.ACTION_MOVE:  
  121.   
  122.             if (!mScroller.isFinished())  
  123.             {  
  124.                 mScroller.abortAnimation();  
  125.             }  
  126.   
  127.             int dy = mLastY - y;  
  128.             // 邊界值檢查  
  129.             int scrollY = getScrollY();  
  130.             // 已經到達頂端,下拉多少,就往上滾動多少  
  131.             if (dy < 0 && scrollY + dy < 0)  
  132.             {  
  133.                 dy = -scrollY;  
  134.             }  
  135.             // 已經到達底部,上拉多少,就往下滾動多少  
  136.             if (dy > 0 && scrollY + dy > getHeight() - mScreenHeight)  
  137.             {  
  138.                 dy = getHeight() - mScreenHeight - scrollY;  
  139.             }  
  140.   
  141.             scrollBy(0, dy);  
  142.             mLastY = y;  
  143.             break;  
  144.         case MotionEvent.ACTION_UP:  
  145.   
  146.             mScrollEnd = getScrollY();  
  147.   
  148.             int dScrollY = mScrollEnd - mScrollStart;  
  149.   
  150.             if (wantScrollToNext())// 往上滑動  
  151.             {  
  152.                 if (shouldScrollToNext())  
  153.                 {  
  154.                     mScroller.startScroll(0, getScrollY(), 0, mScreenHeight - dScrollY);  
  155.   
  156.                 } else  
  157.                 {  
  158.                     mScroller.startScroll(0, getScrollY(), 0, -dScrollY);  
  159.                 }  
  160.   
  161.             }  
  162.   
  163.             if (wantScrollToPre())// 往下滑動  
  164.             {  
  165.                 if (shouldScrollToPre())  
  166.                 {  
  167.                     mScroller.startScroll(0, getScrollY(), 0, -mScreenHeight - dScrollY);  
  168.   
  169.                 } else  
  170.                 {  
  171.                     mScroller.startScroll(0, getScrollY(), 0, -dScrollY);  
  172.                 }  
  173.             }  
  174.             isScrolling = true;  
  175.             postInvalidate();  
  176.             recycleVelocity();  
  177.             break;  
  178.         }  
  179.   
  180.         return true;  
  181.     }  
  182.   
  183.     /** 
  184.      * 根據滾動距離判斷是否能夠滾動到下一頁 
  185.      *  
  186.      * @return 
  187.      */  
  188.     private boolean shouldScrollToNext()  
  189.     {  
  190.         return mScrollEnd - mScrollStart > mScreenHeight / 2 || Math.abs(getVelocity()) > 600;  
  191.     }  
  192.   
  193.     /** 
  194.      * 根據用戶滑動,判斷用戶的意圖是否是滾動到下一頁 
  195.      *  
  196.      * @return 
  197.      */  
  198.     private boolean wantScrollToNext()  
  199.     {  
  200.         return mScrollEnd > mScrollStart;  
  201.     }  
  202.   
  203.     /** 
  204.      * 根據滾動距離判斷是否能夠滾動到上一頁 
  205.      *  
  206.      * @return 
  207.      */  
  208.     private boolean shouldScrollToPre()  
  209.     {  
  210.         return -mScrollEnd + mScrollStart > mScreenHeight / 2 || Math.abs(getVelocity()) > 600;  
  211.     }  
  212.   
  213.     /** 
  214.      * 根據用戶滑動,判斷用戶的意圖是否是滾動到上一頁 
  215.      *  
  216.      * @return 
  217.      */  
  218.     private boolean wantScrollToPre()  
  219.     {  
  220.         return mScrollEnd < mScrollStart;  
  221.     }  
  222.   
  223.     @Override  
  224.     public void computeScroll()  
  225.     {  
  226.         super.computeScroll();  
  227.         if (mScroller.computeScrollOffset())  
  228.         {  
  229.             scrollTo(0, mScroller.getCurrY());  
  230.             postInvalidate();  
  231.         } else  
  232.         {  
  233.   
  234.             int position = getScrollY() / mScreenHeight;  
  235.   
  236.             Log.e("xxx", position + "," + currentPage);  
  237.             if (position != currentPage)  
  238.             {  
  239.                 if (mOnPageChangeListener != null)  
  240.                 {  
  241.                     currentPage = position;  
  242.                     mOnPageChangeListener.onPageChange(currentPage);  
  243.                 }  
  244.             }  
  245.   
  246.             isScrolling = false;  
  247.         }  
  248.   
  249.     }  
  250.   
  251.     /** 
  252.      * 獲取y方向的加速度 
  253.      *  
  254.      * @return 
  255.      */  
  256.     private int getVelocity()  
  257.     {  
  258.         mVelocityTracker.computeCurrentVelocity(1000);  
  259.         return (int) mVelocityTracker.getYVelocity();  
  260.     }  
  261.   
  262.     /** 
  263.      * 釋放資源 
  264.      */  
  265.     private void recycleVelocity()  
  266.     {  
  267.         if (mVelocityTracker != null)  
  268.         {  
  269.             mVelocityTracker.recycle();  
  270.             mVelocityTracker = null;  
  271.         }  
  272.     }  
  273.   
  274.     /** 
  275.      * 初始化加速度檢測器 
  276.      *  
  277.      * @param event 
  278.      */  
  279.     private void obtainVelocity(MotionEvent event)  
  280.     {  
  281.         if (mVelocityTracker == null)  
  282.         {  
  283.             mVelocityTracker = VelocityTracker.obtain();  
  284.         }  
  285.         mVelocityTracker.addMovement(event);  
  286.     }  
  287.   
  288.     /** 
  289.      * 設置回調接口 
  290.      *  
  291.      * @param onPageChangeListener 
  292.      */  
  293.     public void setOnPageChangeListener(OnPageChangeListener onPageChangeListener)  
  294.     {  
  295.         mOnPageChangeListener = onPageChangeListener;  
  296.     }  
  297.   
  298.     /** 
  299.      * 回調接口 
  300.      *  
  301.      * @author zhy 
  302.      *  
  303.      */  
  304.     public interface OnPageChangeListener  
  305.     {  
  306.         void onPageChange(int currentPage);  
  307.     }  
  308. }  

註釋還是相當詳細的,我簡單描述一下,Action_down時獲得當前的scrollY,然後Action_move時,根據移動的距離不斷scrollby就行了,當前處理了一下邊界判斷,在Action_up中再次獲得scrollY,兩個的scrollY進行對比,然後根據移動的距離與方向決定最後的動作。

3、主Activity

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. package com.example.verticallinearlayout;  
  2.   
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5. import android.widget.Toast;  
  6.   
  7. import com.example.verticallinearlayout.VerticalLinearLayout.OnPageChangeListener;  
  8.   
  9. public class MainActivity extends Activity  
  10. {  
  11.     private VerticalLinearLayout mMianLayout;  
  12.   
  13.     @Override  
  14.     protected void onCreate(Bundle savedInstanceState)  
  15.     {  
  16.         super.onCreate(savedInstanceState);  
  17.         setContentView(R.layout.activity_main);  
  18.   
  19.         mMianLayout = (VerticalLinearLayout) findViewById(R.id.id_main_ly);  
  20.         mMianLayout.setOnPageChangeListener(new OnPageChangeListener()  
  21.         {  
  22.             @Override  
  23.             public void onPageChange(int currentPage)  
  24.             {  
  25. //              mMianLayout.getChildAt(currentPage);  
  26.                 Toast.makeText(MainActivity.this"第"+(currentPage+1)+"頁", Toast.LENGTH_SHORT).show();  
  27.             }  
  28.         });  
  29.     }  
  30.   
  31. }  

爲了提供可擴展性,還是定義了回調接口,完全可以把這個當成一個垂直的ViewPager使用。

總結下:

Scroller這個輔助類還是相當好用的,原理我簡單說一下:每次滾動時,讓Scroller進行滾動,然後調用postInvalidate方法,這個方法會引發調用onDraw方法,onDraw方法中會去調用computeScroll方法,然後我們在computScroll中判斷,Scroller的滾動是否結束,沒有的話,把當前的View滾動到現在Scroller的位置,然後繼續調用postInvalidate,這樣一個循環的過程。

畫張圖方便大家理解,ps:沒找到什麼好的畫圖工具,那rose隨便畫了,莫計較。

發佈了4 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章