安卓開發之ViewDragHelper的使用及自定義可下拉展示內容的ViewGroup

cxmscb發表於2016-08-22

一、ViewDragHelper

一個自定義ViewGroup的工具類,它提供了許多有用的方法和狀態允許使用者去拖拽和繪製子View在自定義ViewGroup中的軌跡和位置。

  1. ViewDragHelper可以使用靜態方法建立一個例項:

    ViewDragHelper.create(ViewGroup forParent,int sensitiveity,ViewDragHelper.Callback cb)
    
  2. 在自定義ViewGroup中,ViewDragHelper可以幫助我們來分析手勢和處理拖動:

    @Override
    public boolean onTouchEvent(MotionEvent event) {
            try {
            //處理觸控事件
            mDragHelper.processTouchEvent(event);
            } catch (Exception e) {
            e.printStackTrace();
            }
            //返回true,
            return true;
    }
    
  3. 使用ViewDragHelper來動態移動自定義ViewGroup中的控制元件:

    public boolean smoothSlideViewTo(View child, int finalLeft, int finalTop)
    
    // Animate the view child to the given (left, top) position.
    // 返回true 代表還沒有移動到指定的位置,需要重新整理介面,繼續移動
    // 返回false 就停止工作
    
  4. 使用ViewDragHelper滑動邊緣監聽:

    // 監聽左邊緣滑動
    setEdgeTrackingEnabled(ViewDragHelper.EDGE_LEFT);
    

二、 ViewDragHelper.Callback

ViewDragHelper.Callback整合了許多可覆寫的方法,所有移動的控制在ViewDragHelper.Callback裡面來實現。

  1. 是否可以捕捉ViewGroup中的子元件:

    public boolean tryCaptureView(View child, int pointerId) {
    
    //返回true,就代表著可對該子元件處理滑動事件。否則就不會處理。 
    
    return true;
    //只對特定的元件捕捉 return speChild == child;
    
    }
    

    // 使用ViewDragHelper的captureChildView捕捉子元件,該方法可以繞過tryCaptureView方法

  2. clampViewPositionHorizontal[Vertical]:

    處理子元件在水平或者豎直方向的滑動限制,在這個方法內部做子元件的邊界處理,就是確保子元件不會滑過界。

    例如在豎直方向進行滑動時,一般先獲取控制元件可滑動到的頂端Y值底端Y值,再進行一個取值

    @Override
    public int clampViewPositionVertical(View child, int top, int dy) {
    
    //手指觸控移動時實時回撥, top表示要到的y位置
    
        int topBound = ...;
        int bottomBound = ...;
        return Math.min(Math.max(topBound, top), bottomBound);
    
    }
    
  3. onViewPositionChanged
    當前拖動的子元件位置變化時呼叫的方法。一般在該方法裡調整其他子元件的位置。

    @Override
    public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
    
        //changedView為當前位置發生改變的View,left,top分別為該View的left和top座標
    
    } 
    
  4. onViewReleased

    當手指釋放的時候會呼叫的方法。在這個方法裡實現鬆開時的滑動效果。

    @Override
    public void onViewReleased(View releasedChild, float xvel, float yvel) {
    
        //released 為釋放的View,xvel,yvel分別為該手指離開時滑動和豎直滑動的速度
    
    } 
    
  5. getViewVertical[Horizontal]DragRangeHorizontal

     @Override
        public int getViewVerticalDragRange(View child) {
           //返回當前捕捉的child子元件的豎直滑動範圍
            return ...;
        }
    
  6. onEdgeDragStarted(int edgeFlags, int pointerId)

    // 邊緣滑動時回撥
    @Override
    public void onEdgeDragStarted(int edgeFlags, int pointerId) {
       // edgeFlags為邊緣滑動的方法標誌
    
    }
    

    ……

三、ViewDragHelper的使用

自定義可下拉展示內容的的ViewGroup

效果圖:

這裡寫圖片描述

一、自定義ViewGroup:DragDownLayout

可支援padding和子元件寬高的wrap_content

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.ViewDragHelper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

/**
 * Created by cxm on 2016/8/22.
 */
public class DragDownLayout extends ViewGroup {

    private ViewDragHelper dragHelper;
    private View mDragbar, mContentView;
    private int dragRange;
    private OnOpenListener mOnOpenListener;
    private OnCloseListener mOnCloseListener;

    private boolean isOpen;//是否開啟著

    public DragDownLayout(Context context) {
        super(context);
        init();
    }

    public DragDownLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public DragDownLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public DragDownLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    private void init() {
        dragHelper = ViewDragHelper.create(this, mCallback);
    }


    @Override
    protected void onLayout(boolean b, int l, int t, int r, int bo) {

        mDragbar.layout(getPaddingLeft(), getPaddingTop(), getWidth()-getPaddingRight(), mDragbar.getMeasuredHeight()+getPaddingTop());

        mContentView.layout(getPaddingLeft(), getPaddingTop()-mContentView.getMeasuredHeight(), getWidth()-getPaddingRight(), getPaddingTop());

    }


    @Override
    public boolean onInterceptHoverEvent(MotionEvent event) {
        final int action = MotionEventCompat.getActionMasked(event);
        if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
            dragHelper.cancel();
            return false;
        }
        return dragHelper.shouldInterceptTouchEvent(event);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        dragHelper.processTouchEvent(event);
        return true;
    }

    private ViewDragHelper.Callback mCallback = new ViewDragHelper.Callback() {

        @Override
        public boolean tryCaptureView(View child, int pointerId) {
            return child == mDragbar;
        }



        @Override
        public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {

            // top為mDragbar的top值
            mContentView.layout(getPaddingLeft(), top-mContentView.getHeight(), getWidth()-getPaddingRight(), top );

        }


        @Override
        public int clampViewPositionVertical(View child, int top, int dy) {
            int topBound = getPaddingTop();//頂端邊界
            int bottomBound = getHeight() - mDragbar.getHeight()-getPaddingBottom();//底端邊界
            return Math.min(Math.max(topBound, top), bottomBound);
        }


    @Override
        public int clampViewPositionHorizontal(View child, int left, int dx) {
            // 禁止水平滑動
            return getPaddingLeft();
        }


        @Override
        public int getViewVerticalDragRange(View child) {
            dragRange = mContentView.getMeasuredHeight();
            return dragRange;
        }




        @Override
        public void onViewReleased(View releasedChild, float xvel, float yvel) {

            if (mContentView.getBottom() - getPaddingTop() > mContentView.getHeight() / 2) {
                smoothToBottom();
            } else if (mContentView.getBottom() - getPaddingTop() <= mContentView.getHeight() / 2) {
                smoothToTop();
            }
            invalidate();
        }
    };


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        mDragbar = getChildAt(0);
        mContentView = getChildAt(1);


        measureChild(mDragbar,widthMeasureSpec,heightMeasureSpec);

        int dragBarHeight = mDragbar.getMeasuredHeight();


        measureChild(mContentView,widthMeasureSpec,heightMeasureSpec);

        int contentHeight = mContentView.getMeasuredHeight();


        setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), dragBarHeight+contentHeight+getPaddingBottom()+getPaddingTop());


    }




    private void smoothToTop() {
        if (dragHelper.smoothSlideViewTo(mDragbar, getPaddingLeft(), getPaddingTop())) {
            ViewCompat.postInvalidateOnAnimation(this);
            isOpen = false;
            if(mOnCloseListener!=null) mOnCloseListener.close();
        }
    }

    private void smoothToBottom() {
        if (dragHelper.smoothSlideViewTo(mDragbar, getPaddingLeft(), getHeight()-getPaddingBottom()-mDragbar.getHeight())) {
            ViewCompat.postInvalidateOnAnimation(this);
            isOpen = true;
            if(mOnOpenListener!=null) mOnOpenListener.open();
        }
    }

    @Override
    public void computeScroll() {
        super.computeScroll();
        if (dragHelper.continueSettling(true)) {
            ViewCompat.postInvalidateOnAnimation(this);
        }
    }

    public boolean isOpen(){
        return isOpen;
    }

    public void openContent(){
        if(!isOpen) smoothToBottom();
    }

    public void closeContent(){
        if(isOpen) smoothToTop();
    }

    public interface OnOpenListener{
        void open();
    }

    public interface OnCloseListener{
        void close();
    }



    public void setOnOpenListener(OnOpenListener mOnOpenListener) {
        this.mOnOpenListener = mOnOpenListener;
    }

    public void setOnCloseListener(OnCloseListener mOnCloseListener) {
        this.mOnCloseListener = mOnCloseListener;
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        if (getChildCount() != 2) {
            throw new IllegalStateException("Just contain two Views/ViewGroups ");
        }
    }
}

二、在xml佈局檔案中使用DragDownLayout

支援DragDownLayout的padding,沒有支援子View的margin。

拖拽控制元件和內容控制元件的高度可wrap_content / 具體值,寬度需為match_parent。

<com.cxmscb.cxm.dtest.DragDownLayout
    android:id="@+id/myDragDownLayout"
    android:background="#e0ffff"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:background="#e000ff"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:text="歡迎"
        android:textColor="#ffffff"
        android:gravity="center_vertical"
        android:paddingLeft="15dp"
        android:textSize="19sp" />

    <TextView
        android:id="@+id/content"
        android:background="#e000ff"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:text="Content"
        android:gravity="center"
        android:textSize="20sp"/>

</com.cxmscb.cxm.dtest.DragDownLayout>

三、對DragDownLayout設定監聽

mDragDownLayout = (DragDownLayout) findViewById(R.id.myDragDownLayout);

mDragDownLayout.setOnOpenListener(new DragDownLayout.OnOpenListener() {
        @Override
        public void open() {
            Toast.makeText(MainActivity.this,"open",Toast.LENGTH_SHORT).show();
        }
    });

Github:DragDownLayout

相關文章