效果图
实现功能
1,可以向左滑动,右侧出现删除
2,向左滑动如果删除出现一大半,松手打开删除,反之关闭删除
3,应用场景
微信消息的删除功能
实现原理
1,外面是一个ListView
2,条目是一个自定义控件继承ViewGroup
1,左边一个TextView,右侧屏幕外也有一个TextView
2,所以继承ViewGroup
实现步骤
1,创建一个SlideDeleteView类
1,构造方法要关联
public class SlideDelete extends ViewGroup {
private View leftView;
private View rightView;
private ViewDragHelper helper;
public SlideDelete (Context context) {
this (context,null );
}
public SlideDelete (Context context, AttributeSet attrs) {
this (context, attrs,0 );
}
public SlideDelete (Context context, AttributeSet attrs, int defStyleAttr) {
super (context, attrs, defStyleAttr);
helper = ViewDragHelper.create(this , callback);
}
}
2,在布局文件中设置SlideDeleteView里面的子View
SlideDeleteView height=80
TextView
width:matchParent
height:matchparent
TextView
<com .example .movedelete .SlideDelete
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="80dp" >
<TextView
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="#33000000"
android:text="第0个条目"
android:textColor="#fff"
android:textSize="20sp" />
<TextView
android:id="@+id/delete"
android:layout_width="80dp"
android:layout_height="match_parent"
android:background="#f00"
android:gravity="center"
android:text="删除"
android:textColor="#fff"
android:textSize="20sp" />
</com .example .movedelete .SlideDelete >
3,重写onMeasure,给子View进行测量
protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {
measureChildren(widthMeasureSpec,heightMeasureSpec);
super .onMeasure(widthMeasureSpec, heightMeasureSpec);
}
4,重写onLayout,给子View进行布局
注意事项:
要设置leftView,也要设置rightView,不要都写成leftView了
protected void onLayout (boolean changed, int l, int t, int r, int b) {
leftView = getChildAt(0 );
rightView = getChildAt(1 );
int leftL = 0 ;
int leftT = 0 ;
int leftR = leftView.getMeasuredWidth();
int leftB = leftView.getMeasuredHeight();
leftView.layout(leftL,leftT,leftR,leftB);
int rightL = leftView.getMeasuredWidth();
int rightT = 0 ;
int rightR = leftView.getMeasuredWidth()+ rightView.getMeasuredWidth();
int rightB = rightView.getMeasuredHeight();
rightView.layout(rightL,rightT,rightR,rightB);
}
5,设置View的滑动事件onTouchEvent,实现滑动
1,因为要滑动,所以消费该事件返回true
2,使用ViewDragHelper来实现滑动效果
注意事项:
只能实现leftView的滑动,右侧RightView看不到所以滑动不了
只能给滑动的View设置监听,当滑动的时候,重新设置另一个View的布局跟着滑动
@Override
public boolean onTouchEvent (MotionEvent event ) {
helper.processTouchEvent(event );
return true