开发中经常会遇到下面这样的卡片式拖动效果:
借助系统提供的ViewDragHelper实现这个需求很简单。
public class VerticalDragListView extends FrameLayout {
private ViewDragHelper mViewDragHelper;
public VerticalDragListView(@NonNull Context context) {
this(context,null);
}
public VerticalDragListView(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs,0);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mViewDragHelper.processTouchEvent(event);
//ViewGroup消费事件
return true;
}
public VerticalDragListView(@NonNull Context context,
@Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mViewDragHelper = ViewDragHelper.create(this,
1.0f, new ViewDragHelper.Callback() {
@Override
public boolean tryCaptureView(@NonNull View child, int pointerId) {
//子View都可拖动
return true;
}
//竖直方向拖动
@Override
public int clampViewPositionVertical(@NonNull View child, int top, int dy) {
return top;
}
//水平方向拖动
@Override
public int clampViewPositionHorizontal(@NonNull View child, int left, int dx) {
return left;
}
});
}
}
添加到布局中:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.example.a01.VerticalDragListView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="@color/colorAccent"
android:text="后面"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="300dp"
android:background="@color/colorPrimary"
android:text="前面"
/>
</com.example.a01.VerticalDragListView>
</RelativeLayout>