在安卓中使用DragViewHelper

来源:互联网 发布:人肉 知乎 编辑:程序博客网 时间:2024/06/04 19:33

在安卓的布局中,个人比较喜欢使用DrawerLayout,而在查看它的源码,可以看到其实安卓是运用ViewDragHelper来处理进行拖动处理。

package com.example.dragmessage;

import android.annotation.SuppressLint;
import android.content.Context;
import android.support.v4.widget.ViewDragHelper;
import android.support.v4.widget.ViewDragHelper.Callback;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;

public class DragView extends LinearLayout {

/** * 视图拖动控件 * */ViewDragHelper drag;@SuppressLint("NewApi") public DragView(Context context, AttributeSet attrs, int defStyle) {    super(context, attrs, defStyle);    // TODO Auto-generated constructor stub    init();}public DragView(Context context, AttributeSet attrs) {    this(context, attrs,0);    // TODO Auto-generated constructor stub}public DragView(Context context) {    this(context,null);    // TODO Auto-generated constructor stub}private void init() {    // TODO Auto-generated method stub    //对拖动控件进行初始化,传入父控件,回调函数    drag=ViewDragHelper.create(this, new Callback() {        /****         * 控件是否可以捕捉         * */        @Override        public boolean tryCaptureView(View arg0, int arg1) {            // TODO Auto-generated method stub            return true;        }        /****         * 控件位置发生改变         * */        @Override        public void onViewPositionChanged(View changedView, int left,                int top, int dx, int dy) {            // TODO Auto-generated method stub            super.onViewPositionChanged(changedView, left, top, dx, dy);        }        /***         * 控件s水平位置发生改变         * */        @Override        public int clampViewPositionHorizontal(View child, int left, int dx) {            // TODO Auto-generated method stub            return left;        }        /***         * 控件垂直位置发生改变         * */        @Override        public int clampViewPositionVertical(View child, int top, int dy) {            // TODO Auto-generated method stub            return top;        }    });}@Overridepublic boolean onInterceptTouchEvent(MotionEvent ev) {    // TODO Auto-generated method stub    /*..将点击事件拦截交给dragview处理.*/    return drag.shouldInterceptTouchEvent(ev);}@Overridepublic boolean onTouchEvent(MotionEvent event) {    // TODO Auto-generated method stub    /*进行拖动事件*/    drag.processTouchEvent(event);    return true;}

}

.xml

0 0
原创粉丝点击