Android · 2015年3月4日 0

Android自定义控件实战——仿多看阅读平移翻页

转载请声明出处http://blog.csdn.net/zhongkejingwang/article/details/38728119

之前自己做的一个APP需要用到翻页阅读,网上看过立体翻页效果,不过bug太多了还不兼容。看了一下多看阅读翻页是采用平移翻页的,于是就仿写了一个平移翻页的控件。效果如下:

在翻页时页面右边缘绘制了阴影,效果还不错。要实现这种平移翻页控件并不难,只需要定义一个布局管理页面就可以了。具体实现上有以下难点:

1、循环翻页,页面的重复利用。

2、在翻页时过滤掉多点触碰。

3、采用setAdapter的方式设置页面布局和数据。

下面就来一一解决这几个难点。首先看循环翻页问题,怎么样能采用较少的页面实现这种翻页呢?由于屏幕上每次只能显示一张完整的页面,翻过去的页面也看不到,所以可以把翻过去的页面拿来重复利用,不必每次都new一个页面,所以,我只用了三张页面实现循环翻页。要想重复利用页面,首先要知道页面在布局中序号和对应的层次关系,比如一个父控件的子view的序号越大就位于越上层。循环利用页面的原理图如下:

向右翻页时状态图是这样的,只用了0、1、2三张页面,页面序号为2的位于最上层,我把它隐藏在左边,所以看到的只有页面1,页面0在1下面挡着也看不到,向右翻页时,页面2被滑到屏幕中,这时候把页面0的内容替换成页面2的前一页内容,把它放到之前页面2的位置,这时,状态又回到了初始状态,又可以继续向右翻页了!

向左翻页时是这样的,初始状态还是一样,当页面1被往左翻过时,看到的是页面0,这时候页面0下面已经没有页面了,而页面2已经用不到了,这时候把页面2放到页面0下面,这时候状态又回到了初始状态,就可以继续往左翻页了。

类似于这种循环效果的实现我一直用的解决方案都是将选中的置于最中间,比如原理图中的页面1,每次翻页完成后可见的都是页面1。在滚动选择器PickerView中也是同样的方案。这就解决了页面的重复利用问题了。

解决难点2 翻页时过滤多点触碰这个问题在仿淘宝商品浏览界面中已经解决过了,就是用一个控制变量mEvents过滤掉pointer down或up后到来的第一个move事件。

解决难点3 采用adapter方式设置页面的布局和数据。这个在Android的AdapterView里用到的,但是我没有看它的adapter机制,太复杂了,我就搞了个简单的adapter,如下:

PageAdapter.java:

  1. package com.jingchen.pagerdemo;
  2. import android.view.View;
  3. public abstract class PageAdapter
  4. {
  5.     /**
  6.      * @return 页面view
  7.      */
  8.     public abstract View getView();
  9.     public abstract int getCount();
  10.     /**
  11.      * 将内容添加到view中
  12.      * 
  13.      * @param view
  14.      *            包含内容的view
  15.      * @param position
  16.      *            第position页
  17.      */
  18.     public abstract void addContent(View view, int position);
  19. }

这是一个抽象类,getView()用于返回页面的布局,getCount()返回数据总共需要多少页,addContent(View view, int position)这个是每翻过一页后将会被调用来请求页面数据的,参数view就是页面,position是表明第几页。待会儿会在自定义布局中定义setAdapter方法设置设配器。

OK,难点都解决了,自定义一个布局叫ScanView继承自RelativeLayout:

ScanView.java:

  1. package com.jingchen.pagerdemo;
  2. import java.util.Timer;
  3. import java.util.TimerTask;
  4. import android.content.Context;
  5. import android.graphics.Canvas;
  6. import android.graphics.LinearGradient;
  7. import android.graphics.Paint;
  8. import android.graphics.Paint.Style;
  9. import android.graphics.RectF;
  10. import android.graphics.Shader.TileMode;
  11. import android.os.Handler;
  12. import android.os.Message;
  13. import android.util.AttributeSet;
  14. import android.util.Log;
  15. import android.view.MotionEvent;
  16. import android.view.VelocityTracker;
  17. import android.view.View;
  18. import android.widget.RelativeLayout;
  19. /**
  20.  * @author chenjing
  21.  *
  22.  */
  23. public class ScanView extends RelativeLayout
  24. {
  25.     public static final String TAG = “ScanView”;
  26.     private boolean isInit = true;
  27.     // 滑动的时候存在两页可滑动,要判断是哪一页在滑动
  28.     private boolean isPreMoving = true, isCurrMoving = true;
  29.     // 当前是第几页
  30.     private int index;
  31.     private float lastX;
  32.     // 前一页,当前页,下一页的左边位置
  33.     private int prePageLeft = 0, currPageLeft = 0, nextPageLeft = 0;
  34.     // 三张页面
  35.     private View prePage, currPage, nextPage;
  36.     // 页面状态
  37.     private static final int STATE_MOVE = 0;
  38.     private static final int STATE_STOP = 1;
  39.     // 滑动的页面,只有前一页和当前页可滑
  40.     private static final int PRE = 2;
  41.     private static final int CURR = 3;
  42.     private int state = STATE_STOP;
  43.     // 正在滑动的页面右边位置,用于绘制阴影
  44.     private float right;
  45.     // 手指滑动的距离
  46.     private float moveLenght;
  47.     // 页面宽高
  48.     private int mWidth, mHeight;
  49.     // 获取滑动速度
  50.     private VelocityTracker vt;
  51.     // 防止抖动
  52.     private float speed_shake = 20;
  53.     // 当前滑动速度
  54.     private float speed;
  55.     private Timer timer;
  56.     private MyTimerTask mTask;
  57.     // 滑动动画的移动速度
  58.     public static final int MOVE_SPEED = 10;
  59.     // 页面适配器
  60.     private PageAdapter adapter;
  61.     /**
  62.      * 过滤多点触碰的控制变量
  63.      */
  64.     private int mEvents;
  65.     public void setAdapter(ScanViewAdapter adapter)
  66.     {
  67.         removeAllViews();
  68.         this.adapter = adapter;
  69.         prePage = adapter.getView();
  70.         addView(prePage, 0new LayoutParams(LayoutParams.MATCH_PARENT,
  71.                 LayoutParams.MATCH_PARENT));
  72.         adapter.addContent(prePage, index – 1);
  73.         currPage = adapter.getView();
  74.         addView(currPage, 0new LayoutParams(LayoutParams.MATCH_PARENT,
  75.                 LayoutParams.MATCH_PARENT));
  76.         adapter.addContent(currPage, index);
  77.         nextPage = adapter.getView();
  78.         addView(nextPage, 0new LayoutParams(LayoutParams.MATCH_PARENT,
  79.                 LayoutParams.MATCH_PARENT));
  80.         adapter.addContent(nextPage, index + 1);
  81.     }
  82.     /**
  83.      * 向左滑。注意可以滑动的页面只有当前页和前一页
  84.      * 
  85.      * @param which
  86.      */
  87.     private void moveLeft(int which)
  88.     {
  89.         switch (which)
  90.         {
  91.         case PRE:
  92.             prePageLeft -= MOVE_SPEED;
  93.             if (prePageLeft < -mWidth)
  94.                 prePageLeft = -mWidth;
  95.             right = mWidth + prePageLeft;
  96.             break;
  97.         case CURR:
  98.             currPageLeft -= MOVE_SPEED;
  99.             if (currPageLeft < -mWidth)
  100.                 currPageLeft = -mWidth;
  101.             right = mWidth + currPageLeft;
  102.             break;
  103.         }
  104.     }
  105.     /**
  106.      * 向右滑。注意可以滑动的页面只有当前页和前一页
  107.      * 
  108.      * @param which
  109.      */
  110.     private void moveRight(int which)
  111.     {
  112.         switch (which)
  113.         {
  114.         case PRE:
  115.             prePageLeft += MOVE_SPEED;
  116.             if (prePageLeft > 0)
  117.                 prePageLeft = 0;
  118.             right = mWidth + prePageLeft;
  119.             break;
  120.         case CURR:
  121.             currPageLeft += MOVE_SPEED;
  122.             if (currPageLeft > 0)
  123.                 currPageLeft = 0;
  124.             right = mWidth + currPageLeft;
  125.             break;
  126.         }
  127.     }
  128.     /**
  129.      * 当往回翻过一页时添加前一页在最左边
  130.      */
  131.     private void addPrePage()
  132.     {
  133.         removeView(nextPage);
  134.         addView(nextPage, –1new LayoutParams(LayoutParams.MATCH_PARENT,
  135.                 LayoutParams.MATCH_PARENT));
  136.         // 从适配器获取前一页内容
  137.         adapter.addContent(nextPage, index – 1);
  138.         // 交换顺序
  139.         View temp = nextPage;
  140.         nextPage = currPage;
  141.         currPage = prePage;
  142.         prePage = temp;
  143.         prePageLeft = -mWidth;
  144.     }
  145.     /**
  146.      * 当往前翻过一页时,添加一页在最底下
  147.      */
  148.     private void addNextPage()
  149.     {
  150.         removeView(prePage);
  151.         addView(prePage, 0new LayoutParams(LayoutParams.MATCH_PARENT,
  152.                 LayoutParams.MATCH_PARENT));
  153.         // 从适配器获取后一页内容
  154.         adapter.addContent(prePage, index + 1);
  155.         // 交换顺序
  156.         View temp = currPage;
  157.         currPage = nextPage;
  158.         nextPage = prePage;
  159.         prePage = temp;
  160.         currPageLeft = 0;
  161.     }
  162.     Handler updateHandler = new Handler()
  163.     {
  164.         @Override
  165.         public void handleMessage(Message msg)
  166.         {
  167.             if (state != STATE_MOVE)
  168.                 return;
  169.             // 移动页面
  170.             // 翻回,先判断当前哪一页处于未返回状态
  171.             if (prePageLeft > -mWidth && speed <= 0)
  172.             {
  173.                 // 前一页处于未返回状态
  174.                 moveLeft(PRE);
  175.             } else if (currPageLeft < 0 && speed >= 0)
  176.             {
  177.                 // 当前页处于未返回状态
  178.                 moveRight(CURR);
  179.             } else if (speed < 0 && index < adapter.getCount())
  180.             {
  181.                 // 向左翻,翻动的是当前页
  182.                 moveLeft(CURR);
  183.                 if (currPageLeft == (-mWidth))
  184.                 {
  185.                     index++;
  186.                     // 翻过一页,在底下添加一页,把最上层页面移除
  187.                     addNextPage();
  188.                 }
  189.             } else if (speed > 0 && index > 1)
  190.             {
  191.                 // 向右翻,翻动的是前一页
  192.                 moveRight(PRE);
  193.                 if (prePageLeft == 0)
  194.                 {
  195.                     index–;
  196.                     // 翻回一页,添加一页在最上层,隐藏在最左边
  197.                     addPrePage();
  198.                 }
  199.             }
  200.             if (right == 0 || right == mWidth)
  201.             {
  202.                 releaseMoving();
  203.                 state = STATE_STOP;
  204.                 quitMove();
  205.             }
  206.             ScanView.this.requestLayout();
  207.         }
  208.     };
  209.     public ScanView(Context context, AttributeSet attrs, int defStyle)
  210.     {
  211.         super(context, attrs, defStyle);
  212.         init();
  213.     }
  214.     public ScanView(Context context)
  215.     {
  216.         super(context);
  217.         init();
  218.     }
  219.     public ScanView(Context context, AttributeSet attrs)
  220.     {
  221.         super(context, attrs);
  222.         init();
  223.     }
  224.     /**
  225.      * 退出动画翻页
  226.      */
  227.     public void quitMove()
  228.     {
  229.         if (mTask != null)
  230.         {
  231.             mTask.cancel();
  232.             mTask = null;
  233.         }
  234.     }
  235.     private void init()
  236.     {
  237.         index = 1;
  238.         timer = new Timer();
  239.         mTask = new MyTimerTask(updateHandler);
  240.     }
  241.     /**
  242.      * 释放动作,不限制手滑动方向
  243.      */
  244.     private void releaseMoving()
  245.     {
  246.         isPreMoving = true;
  247.         isCurrMoving = true;
  248.     }
  249.     @Override
  250.     public boolean dispatchTouchEvent(MotionEvent event)
  251.     {
  252.         if (adapter != null)
  253.             switch (event.getActionMasked())
  254.             {
  255.             case MotionEvent.ACTION_DOWN:
  256.                 lastX = event.getX();
  257.                 try
  258.                 {
  259.                     if (vt == null)
  260.                     {
  261.                         vt = VelocityTracker.obtain();
  262.                     } else
  263.                     {
  264.                         vt.clear();
  265.                     }
  266.                 } catch (Exception e)
  267.                 {
  268.                     e.printStackTrace();
  269.                 }
  270.                 vt.addMovement(event);
  271.                 mEvents = 0;
  272.                 break;
  273.             case MotionEvent.ACTION_POINTER_DOWN:
  274.             case MotionEvent.ACTION_POINTER_UP:
  275.                 mEvents = –1;
  276.                 break;
  277.             case MotionEvent.ACTION_MOVE:
  278.                 // 取消动画
  279.                 quitMove();
  280.                 Log.d(“index”“mEvents = “ + mEvents + “, isPreMoving = “
  281.                         + isPreMoving + “, isCurrMoving = “ + isCurrMoving);
  282.                 vt.addMovement(event);
  283.                 vt.computeCurrentVelocity(500);
  284.                 speed = vt.getXVelocity();
  285.                 moveLenght = event.getX() – lastX;
  286.                 if ((moveLenght > 0 || !isCurrMoving) && isPreMoving
  287.                         && mEvents == 0)
  288.                 {
  289.                     isPreMoving = true;
  290.                     isCurrMoving = false;
  291.                     if (index == 1)
  292.                     {
  293.                         // 第一页不能再往右翻,跳转到前一个activity
  294.                         state = STATE_MOVE;
  295.                         releaseMoving();
  296.                     } else
  297.                     {
  298.                         // 非第一页
  299.                         prePageLeft += (int) moveLenght;
  300.                         // 防止滑过边界
  301.                         if (prePageLeft > 0)
  302.                             prePageLeft = 0;
  303.                         else if (prePageLeft < -mWidth)
  304.                         {
  305.                             // 边界判断,释放动作,防止来回滑动导致滑动前一页时当前页无法滑动
  306.                             prePageLeft = -mWidth;
  307.                             releaseMoving();
  308.                         }
  309.                         right = mWidth + prePageLeft;
  310.                         state = STATE_MOVE;
  311.                     }
  312.                 } else if ((moveLenght < 0 || !isPreMoving) && isCurrMoving
  313.                         && mEvents == 0)
  314.                 {
  315.                     isPreMoving = false;
  316.                     isCurrMoving = true;
  317.                     if (index == adapter.getCount())
  318.                     {
  319.                         // 最后一页不能再往左翻
  320.                         state = STATE_STOP;
  321.                         releaseMoving();
  322.                     } else
  323.                     {
  324.                         currPageLeft += (int) moveLenght;
  325.                         // 防止滑过边界
  326.                         if (currPageLeft < -mWidth)
  327.                             currPageLeft = -mWidth;
  328.                         else if (currPageLeft > 0)
  329.                         {
  330.                             // 边界判断,释放动作,防止来回滑动导致滑动当前页是前一页无法滑动
  331.                             currPageLeft = 0;
  332.                             releaseMoving();
  333.                         }
  334.                         right = mWidth + currPageLeft;
  335.                         state = STATE_MOVE;
  336.                     }
  337.                 } else
  338.                     mEvents = 0;
  339.                 lastX = event.getX();
  340.                 requestLayout();
  341.                 break;
  342.             case MotionEvent.ACTION_UP:
  343.                 if (Math.abs(speed) < speed_shake)
  344.                     speed = 0;
  345.                 quitMove();
  346.                 mTask = new MyTimerTask(updateHandler);
  347.                 timer.schedule(mTask, 05);
  348.                 try
  349.                 {
  350.                     vt.clear();
  351.                     vt.recycle();
  352.                 } catch (Exception e)
  353.                 {
  354.                     e.printStackTrace();
  355.                 }
  356.                 break;
  357.             default:
  358.                 break;
  359.             }
  360.         super.dispatchTouchEvent(event);
  361.         return true;
  362.     }
  363.     /*
  364.      * (非 Javadoc) 在这里绘制翻页阴影效果
  365.      * 
  366.      * @see android.view.ViewGroup#dispatchDraw(android.graphics.Canvas)
  367.      */
  368.     @Override
  369.     protected void dispatchDraw(Canvas canvas)
  370.     {
  371.         super.dispatchDraw(canvas);
  372.         if (right == 0 || right == mWidth)
  373.             return;
  374.         RectF rectF = new RectF(right, 0, mWidth, mHeight);
  375.         Paint paint = new Paint();
  376.         paint.setAntiAlias(true);
  377.         LinearGradient linearGradient = new LinearGradient(right, 0,
  378.                 right + 3600xffbbbbbb0x00bbbbbb, TileMode.CLAMP);
  379.         paint.setShader(linearGradient);
  380.         paint.setStyle(Style.FILL);
  381.         canvas.drawRect(rectF, paint);
  382.     }
  383.     @Override
  384.     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
  385.     {
  386.         super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  387.         mWidth = getMeasuredWidth();
  388.         mHeight = getMeasuredHeight();
  389.         if (isInit)
  390.         {
  391.             // 初始状态,一页放在左边隐藏起来,两页叠在一块
  392.             prePageLeft = -mWidth;
  393.             currPageLeft = 0;
  394.             nextPageLeft = 0;
  395.             isInit = false;
  396.         }
  397.     }
  398.     @Override
  399.     protected void onLayout(boolean changed, int l, int t, int r, int b)
  400.     {
  401.         if (adapter == null)
  402.             return;
  403.         prePage.layout(prePageLeft, 0,
  404.                 prePageLeft + prePage.getMeasuredWidth(),
  405.                 prePage.getMeasuredHeight());
  406.         currPage.layout(currPageLeft, 0,
  407.                 currPageLeft + currPage.getMeasuredWidth(),
  408.                 currPage.getMeasuredHeight());
  409.         nextPage.layout(nextPageLeft, 0,
  410.                 nextPageLeft + nextPage.getMeasuredWidth(),
  411.                 nextPage.getMeasuredHeight());
  412.         invalidate();
  413.     }
  414.     class MyTimerTask extends TimerTask
  415.     {
  416.         Handler handler;
  417.         public MyTimerTask(Handler handler)
  418.         {
  419.             this.handler = handler;
  420.         }
  421.         @Override
  422.         public void run()
  423.         {
  424.             handler.sendMessage(handler.obtainMessage());
  425.         }
  426.     }
  427. }

代码中的注释写的非常多,原理理解了看代码就容易看懂了。写完这个布局后再写一个ScanViewAdapter继承PageAdapter:

  1. package com.jingchen.pagerdemo;
  2. import java.util.List;
  3. import android.content.Context;
  4. import android.content.res.AssetManager;
  5. import android.graphics.Typeface;
  6. import android.view.LayoutInflater;
  7. import android.view.View;
  8. import android.widget.TextView;
  9. public class ScanViewAdapter extends PageAdapter
  10. {
  11.     Context context;
  12.     List<String> items;
  13.     AssetManager am;
  14.     public ScanViewAdapter(Context context, List<String> items)
  15.     {
  16.         this.context = context;
  17.         this.items = items;
  18.         am = context.getAssets();
  19.     }
  20.     public void addContent(View view, int position)
  21.     {
  22.         TextView content = (TextView) view.findViewById(R.id.content);
  23.         TextView tv = (TextView) view.findViewById(R.id.index);
  24.         if ((position – 1) < 0 || (position – 1) >= getCount())
  25.             return;
  26.         content.setText(”    双峰叠障,过天风海雨,无边空碧。月姊年年应好在,玉阙琼宫愁寂。谁唤痴云,一杯未尽,夜气寒无色。碧城凝望,高楼缥缈西北。\n\n    肠断桂冷蟾孤,佳期如梦,又把阑干拍。雾鬓风虔相借问,浮世几回今夕。圆缺睛明,古今同恨,我更长为客。蝉娟明夜,尊前谁念南陌。”);
  27.         tv.setText(items.get(position – 1));
  28.     }
  29.     public int getCount()
  30.     {
  31.         return items.size();
  32.     }
  33.     public View getView()
  34.     {
  35.         View view = LayoutInflater.from(context).inflate(R.layout.page_layout,
  36.                 null);
  37.         return view;
  38.     }
  39. }

这里只是我的demo里写的Adapter,也可以写成带更多内容的Adapter。addContent里带的参数view就是getView里面返回的view,这样就可以根据inflate的布局设置内容了,getView返回的布局page_layout.xml如下:

  1. <RelativeLayout xmlns:android=“http://schemas.android.com/apk/res/android”
  2.     android:layout_width=“match_parent”
  3.     android:layout_height=“match_parent”
  4.     android:background=“@drawable/cover” >
  5.     <TextView
  6.         android:id=“@+id/content”
  7.         android:layout_width=“wrap_content”
  8.         android:layout_height=“wrap_content”
  9.         android:layout_centerHorizontal=“true”
  10.         android:layout_marginTop=“60dp”
  11.         android:padding=“10dp”
  12.         android:textColor=“#000000”
  13.         android:textSize=“22sp” />
  14.     <TextView
  15.         android:id=“@+id/index”
  16.         android:layout_width=“wrap_content”
  17.         android:layout_height=“wrap_content”
  18.         android:layout_alignParentBottom=“true”
  19.         android:layout_centerHorizontal=“true”
  20.         android:layout_marginBottom=“60dp”
  21.         android:textColor=“#000000”
  22.         android:textSize=“30sp” />
  23. </RelativeLayout>

只包含了两个TextView,所以在adapter中可以根据id查找到这两个TextView再给它设置内容。

OK了,MainActivity的布局如下:

  1. <RelativeLayout xmlns:android=“http://schemas.android.com/apk/res/android”
  2.     android:layout_width=“match_parent”
  3.     android:layout_height=“match_parent” >
  4.     <com.jingchen.pagerdemo.ScanView
  5.         android:id=“@+id/scanview”
  6.         android:layout_width=“match_parent”
  7.         android:layout_height=“match_parent” />
  8. </RelativeLayout>

很简单,只包含了ScanView。

MainActivity的代码:

  1. package com.jingchen.pagerdemo;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import android.app.Activity;
  5. import android.os.Bundle;
  6. import android.view.Menu;
  7. public class MainActivity extends Activity
  8. {
  9.     ScanView scanview;
  10.     ScanViewAdapter adapter;
  11.     @Override
  12.     protected void onCreate(Bundle savedInstanceState)
  13.     {
  14.         super.onCreate(savedInstanceState);
  15.         setContentView(R.layout.activity_main);
  16.         scanview = (ScanView) findViewById(R.id.scanview);
  17.         List<String> items = new ArrayList<String>();
  18.         for (int i = 0; i < 8; i++)
  19.             items.add(“第 “ + (i + 1) + ” 页”);
  20.         adapter = new ScanViewAdapter(this, items);
  21.         scanview.setAdapter(adapter);
  22.     }
  23.     @Override
  24.     public boolean onCreateOptionsMenu(Menu menu)
  25.     {
  26.         getMenuInflater().inflate(R.menu.main, menu);
  27.         return true;
  28.     }
  29. }

给ScanView设置Adapter就可以了。

好啦,仿多看的平移翻页就完成了~

源码下载

Share this: