[关闭]
@xujun94 2016-07-17T16:32:35.000000Z 字数 9337 阅读 1753

使用ViewDragHelper打造属于自己的DragLayout(抽屉开关 )


DrawLayout这个自定义的空间很常见,qq,网易新闻,知乎等等,都有这种效果,那这种效果是怎样实现的呢?本篇博客将带你来怎样实现它。

转载请注明原博客地址: http://blog.csdn.net/gdutxiaoxu/article/details/51935896

废话不多说,先来看一下 效果

首先我们先来看一下我们要怎样使用它

其实只需要两个 步骤,使用起来 非常方便

1.在XML文件

DragLayout至少要有两个孩子,且都是 ViewGroup或者ViewGroup的实现类

  1. <com.xujun.drawerLayout.drag.DragLayout
  2. android:id="@+id/dl"
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. xmlns:app="http://schemas.android.com/apk/res-auto"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. android:background="@drawable/bg"
  8. app:range="480"
  9. >
  10. <LinearLayout
  11. android:layout_width="match_parent"
  12. android:layout_height="match_parent"
  13. android:orientation="vertical"
  14. android:paddingBottom="50dp"
  15. android:paddingLeft="10dp"
  16. android:paddingRight="50dp"
  17. android:paddingTop="50dp">
  18. <ImageView
  19. android:layout_width="50dp"
  20. android:layout_height="50dp"
  21. android:src="@drawable/head"/>
  22. <ListView
  23. android:id="@+id/lv_left"
  24. android:layout_width="match_parent"
  25. android:layout_height="match_parent">
  26. </ListView>
  27. </LinearLayout>
  28. <com.xujun.drawerLayout.drag.MyLinearLayout
  29. android:id="@+id/mll"
  30. android:layout_width="match_parent"
  31. android:layout_height="match_parent"
  32. android:background="#ffffff"
  33. android:orientation="vertical">
  34. <RelativeLayout
  35. android:layout_width="match_parent"
  36. android:layout_height="50dp"
  37. android:background="#18B6EF"
  38. android:gravity="center_vertical">
  39. <ImageView
  40. android:id="@+id/iv_header"
  41. android:layout_width="30dp"
  42. android:layout_height="30dp"
  43. android:layout_marginLeft="15dp"
  44. android:src="@drawable/head"/>
  45. <TextView
  46. android:layout_width="wrap_content"
  47. android:layout_height="wrap_content"
  48. android:layout_centerHorizontal="true"
  49. android:text="Header"/>
  50. </RelativeLayout>
  51. <ListView
  52. android:id="@+id/lv_main"
  53. android:layout_width="match_parent"
  54. android:layout_height="match_parent">
  55. </ListView>
  56. </com.xujun.drawerLayout.drag.MyLinearLayout>
  57. </com.xujun.drawerLayout.drag.DragLayout>

在代码中若想为其设置监听器,

分别可以监听打开的 时候,关闭的时候,拖动的时候,可以在里面做相应的处理,同时我还加入了 自定义属性可以通过 app:range="480"或者setRange()方法,即可设置打开抽屉的范围。

  1. mDragLayout.setDragStatusListener(new OnDragStatusChangeListener() {
  2. @Override
  3. public void onOpen() {
  4. Utils.showToast(MainActivity.this, "onOpen");
  5. // 左面板ListView随机设置一个条目
  6. Random random = new Random();
  7. Log.i(TAG, "onOpen:=" +mDragLayout.getRange());
  8. int nextInt = random.nextInt(50);
  9. mLeftList.smoothScrollToPosition(nextInt);
  10. }
  11. @Override
  12. public void onDraging(float percent) {
  13. Log.d(TAG, "onDraging: " + percent);// 0 -> 1
  14. // 更新图标的透明度
  15. // 1.0 -> 0.0
  16. ViewHelper.setAlpha(mHeaderImage, 1 - percent);
  17. }
  18. @Override
  19. public void onClose() {
  20. Utils.showToast(MainActivity.this, "onClose");
  21. // 让图标晃动
  22. ObjectAnimator mAnim = ObjectAnimator.ofFloat(mHeaderImage, "translationX", 15.0f);
  23. mAnim.setInterpolator(new CycleInterpolator(4));
  24. mAnim.setDuration(500);
  25. mAnim.start();
  26. }
  27. });

实现方式

关于ViewDragHelper的一些 讨论

DrawLayout在网上的 实现方式很多,千奇百怪,有一些是直接监听 onTouchEvent事件,处理Activon_Move,Action_Down,Action_up等动作,这样实现的话稍微有点复杂。本篇博客是使用ViewDragHelper来 处理触摸事件和拖拽事件的的,ViewDragHelper是2013Google IO大会推出的,目的是为了给开发者提供一个处理触摸事件,节省开发者的时间。

关于Google官方 关于ViewDragHelper的解释,简单来说就是处理ViewGroup的 触摸事件和拖拽事件

ViewDragHelper is a utility class for writing custom ViewGroups. It offers a number of useful operations and state tracking for allowing a user to drag and reposition views within their parent ViewGroup.

实现思路

  1. public DragLayout(Context context, AttributeSet attrs, int defStyle) {
  2. super(context, attrs, defStyle);
  3. initAttars(context, attrs);
  4. // a.初始化 (通过静态方法)
  5. mDragHelper = ViewDragHelper.create(this, mSensitivity, mCallback);
  6. }
  1. // b.传递触摸事件
  2. @Override
  3. public boolean onInterceptTouchEvent(MotionEvent ev) {
  4. // 传递给mDragHelper
  5. return mDragHelper.shouldInterceptTouchEvent(ev);
  6. }
  7. /***
  8. * 将事件交给mDragHelper处理
  9. *
  10. * @param event
  11. * @return
  12. */
  13. @Override
  14. public boolean onTouchEvent(MotionEvent event) {
  15. try {
  16. mDragHelper.processTouchEvent(event);
  17. } catch (Exception e) {
  18. e.printStackTrace();
  19. }
  20. // 返回true, 持续接受事件
  21. return true;
  22. }
  1. @Override
  2. protected void onFinishInflate() {
  3. super.onFinishInflate();
  4. // 容错性检查 (至少有俩子View, 子View必须是ViewGroup的子类)
  5. if (getChildCount() < 2) {
  6. throw new IllegalStateException("布局至少有俩孩子. Your ViewGroup must have 2 children at " +
  7. "least.");
  8. }
  9. if (!(getChildAt(0) instanceof ViewGroup && getChildAt(1) instanceof ViewGroup)) {
  10. throw new IllegalArgumentException("子View必须是ViewGroup的子类. Your children must be an " +
  11. "instance of ViewGroup");
  12. }
  13. mLeftContent = (ViewGroup) getChildAt(0);
  14. mMainContent = (ViewGroup) getChildAt(1);
  15. }

下面我们一起来看一下这个mCallBack是什么东西

看之前我们需要了解Status和OnDragStatusChangeListener这两个东西。

  1. /**
  2. * 状态枚举
  3. */
  4. public static enum Status {
  5. Close, Open, Draging;
  6. }
  7. /**
  8. * 抽屉开关的监听器
  9. */
  10. public interface OnDragStatusChangeListener {
  11. void onClose();
  12. void onOpen();
  13. void onDraging(float percent);
  14. }

接下来我们来看ViewDragHelper.Callback几个主要的方法


tryCaptureView(View child, int pointerId)
Called when the user's input indicates that they want to capture the given child view with the pointer indicated by pointerId.
onViewCaptured(View capturedChild, int activePointerId)
Called when a child view is captured for dragging or settling.

getViewHorizontalDragRange(View child)
Return the magnitude of a draggable child view's horizontal range of motion in pixels.

clampViewPositionHorizontal(View child, int left, int dx)
Restrict the motion of the dragged child view along the horizontal axis.

onViewPositionChanged(View changedView, int left, int top, int dx, int dy)
Called when the captured view's position changes as the result of a drag or settle.

onViewReleased(View releasedChild, float xvel, float yvel)
Called when the child view is no longer being actively dragged.

谷歌官方的连接;https://developer.android.com/reference/android/support/v4/widget/ViewDragHelper.Callback.html


下面的代码有关于这几个方法的中文解释,这里就不详细讲解了

  1. ViewDragHelper.Callback mCallback = new ViewDragHelper.Callback() {
  2. // d. 重写事件
  3. // 1. 根据返回结果决定当前child是否可以拖拽
  4. // child 当前被拖拽的View
  5. // pointerId 区分多点触摸的id
  6. @Override
  7. public boolean tryCaptureView(View child, int pointerId) {
  8. Log.d(TAG, "tryCaptureView: " + child);
  9. return mToogle;
  10. }
  11. @Override
  12. public void onViewCaptured(View capturedChild, int activePointerId) {
  13. Log.d(TAG, "onViewCaptured: " + capturedChild);
  14. // 当capturedChild被捕获时,调用.
  15. super.onViewCaptured(capturedChild, activePointerId);
  16. }
  17. @Override
  18. public int getViewHorizontalDragRange(View child) {
  19. // 返回拖拽的范围, 不对拖拽进行真正的限制. 仅仅决定了动画执行速度
  20. Log.i(TAG, "getViewHorizontalDragRange:mRange=" +mRange);
  21. return mRange;
  22. }
  23. // 2. 根据建议值 修正将要移动到的(横向)位置 (重要)
  24. // 此时没有发生真正的移动
  25. public int clampViewPositionHorizontal(View child, int left, int dx) {
  26. // child: 当前拖拽的View
  27. // left 新的位置的建议值, dx 位置变化量
  28. // left = oldLeft + dx;
  29. Log.d(TAG, "clampViewPositionHorizontal: "
  30. + "oldLeft: " + child.getLeft() + " dx: " + dx + " left: " + left);
  31. if (child == mMainContent) {
  32. left = fixLeft(left);
  33. }
  34. return left;
  35. }
  36. // 3. 当View位置改变的时候, 处理要做的事情 (更新状态, 伴随动画, 重绘界面)
  37. // 此时,View已经发生了位置的改变
  38. @Override
  39. public void onViewPositionChanged(View changedView, int left, int top,
  40. int dx, int dy) {
  41. // changedView 改变位置的View
  42. // left 新的左边值
  43. // dx 水平方向变化量
  44. super.onViewPositionChanged(changedView, left, top, dx, dy);
  45. Log.d(TAG, "onViewPositionChanged: " + "left: " + left + " dx: " + dx);
  46. int newLeft = left;
  47. if (changedView == mLeftContent) {
  48. // 把当前变化量传递给mMainContent
  49. newLeft = mMainContent.getLeft() + dx;
  50. }
  51. // 进行修正
  52. newLeft = fixLeft(newLeft);
  53. if (changedView == mLeftContent) {
  54. // 当左面板移动之后, 再强制放回去.
  55. mLeftContent.layout(0, 0, 0 + mWidth, 0 + mHeight);
  56. mMainContent.layout(newLeft, 0, newLeft + mWidth, 0 + mHeight);
  57. }
  58. // 更新状态,执行动画
  59. dispatchDragEvent(newLeft);
  60. // 为了兼容低版本, 每次修改值之后, 进行重绘
  61. invalidate();
  62. }
  63. // 4. 当View被释放的时候, 处理的事情(执行动画)
  64. @Override
  65. public void onViewReleased(View releasedChild, float xvel, float yvel) {
  66. // View releasedChild 被释放的子View
  67. // float xvel 水平方向的速度, 向右为+
  68. // float yvel 竖直方向的速度, 向下为+
  69. Log.d(TAG, "onViewReleased: " + "xvel: " + xvel + " yvel: " + yvel);
  70. super.onViewReleased(releasedChild, xvel, yvel);
  71. // 判断执行 关闭/开启
  72. // 先考虑所有开启的情况,剩下的就都是关闭的情况
  73. if (xvel == 0 && mMainContent.getLeft() > mRange / 2.0f) {
  74. open();
  75. } else if (xvel > 0) {
  76. open();
  77. } else {
  78. close();
  79. }
  80. }
  81. @Override
  82. public void onViewDragStateChanged(int state) {
  83. // TODO Auto-generated method stub
  84. super.onViewDragStateChanged(state);
  85. }
  86. };

其实主要思路就是

  1. public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
  2. // 进行修正
  3. newLeft = fixLeft(newLeft);
  4. if (changedView == mLeftContent) {
  5. // 当左面板移动之后, 再强制放回去.
  6. mLeftContent.layout(0, 0, 0 + mWidth, 0 + mHeight);
  7. mMainContent.layout(newLeft, 0, newLeft + mWidth, 0 + mHeight);
  8. if (changedView == mLeftContent) {
  9. // 把当前变化量传递给mMainContent
  10. newLeft = mMainContent.getLeft() + dx;
  11. }
  12. }
  13. // 更新状态,执行动画
  14. dispatchDragEvent(newLeft);
  15. // 为了兼容低版本, 每次修改值之后, 进行重绘
  16. invalidate();
  17. }
  18. protected void dispatchDragEvent(int newLeft) {
  19. float percent = newLeft * 1.0f / mRange;
  20. //0.0f -> 1.0f
  21. Log.d(TAG, "percent: " + percent);
  22. if (mListener != null) {
  23. mListener.onDraging(percent);
  24. }
  25. // 更新状态, 执行回调
  26. Status preStatus = mStatus;
  27. mStatus = updateStatus(percent);
  28. if (mStatus != preStatus) {
  29. // 状态发生变化
  30. if (mStatus == Status.Close) {
  31. // 当前变为关闭状态
  32. if (mListener != null) {
  33. mListener.onClose();
  34. }
  35. } else if (mStatus == Status.Open) {
  36. if (mListener != null) {
  37. mListener.onOpen();
  38. }
  39. }
  40. }
  41. // * 伴随动画:
  42. animViews(percent);
  43. }

转载请注明原博客地址: http://blog.csdn.net/gdutxiaoxu/article/details/51935896

源码下载地址: https://github.com/gdutxiaoxu/drawLayout.git

关于更多自定义View的例子,可查看以下我的一些博客,同时如果大家觉得还可以的,欢迎在github上面 star或者fork,谢谢。

常用的自定义View例子一(FlowLayout)

自定义View常用例子二(点击展开隐藏控件,九宫格图片控件)

常用的自定义View例子三(MultiInterfaceView多界面处理)

常用的自定义控件四(QuickBarView)

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注