ListView侧滑删除操作已经成为了一种常见的交互,一般是从列表控件自身出发,重写ListView实现,比如网上使用频率较高的SwipeMenuListView。
其实还有一种更直观的做法,那就是把焦点放在滑动List Item本身这个操作上来,自定义可以支持侧滑操作的ItemView,即对ListView适配器中的convertView的RootView布局控件进行重写,这样更容易扩展,方便控制列表项哪些可以侧滑,哪些不能滑动,哪些使用左滑,哪些使用右滑等,还减少了代码量。
package com.john.sideslipdemo;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.OvershootInterpolator;
/**
* 继承自ViewGroup,实现滑动出现删除等选项的效果
* Created by john on 16-11-15.
*/
public class SwipeMenuViewGroup extends ViewGroup {
private int mScaleTouchSlop;//为了处理单击事件的冲突
private int mMaxVelocity;//计算滑动速度用
private int mPointerId;//多点触摸只算第一根手指的速度
private int mHeight;//自己的高度
private int mRightMenuWidths; //右侧菜单宽度总和(最大滑动距离)
//滑动判定临界值(右侧菜单宽度的40%) 手指抬起时,超过了展开,没超过收起menu
private int mLimit;
//存储contentView(第一个View)
private View mContentView;
//上一次的xy
private PointF mLastP = new PointF();
private boolean isUnMoved = true;
//判断手指起始落点,如果距离属于滑动了,就屏蔽一切点击事件。
private PointF mFirstP = new PointF();
private boolean isUserSwiped;
//存储的是当前正在展开的View
private static SwipeMenuViewGroup mViewCache;
//防止多只手指一起滑我的flag 在每次down里判断, touch事件结束清空
private static boolean isTouching;
private VelocityTracker mVelocityTracker;//滑动速度变量
/**
* 右滑删除功能的开关,默认开
*/
private boolean isSwipeEnable;
/**
* IOS、QQ式交互,默认开
*/
private boolean isIos;
private boolean iosInterceptFlag;//IOS类型下,是否拦截事件的flag
/**
*左滑右滑的开关,默认左滑打开菜单
*/
private boolean isLeftSwipe;
public SwipeMenuViewGroup(Context context) {
this(context, null);
}
public SwipeMenuViewGroup(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SwipeMenuViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr);
}
public boolean isSwipeEnable() {
return isSwipeEnable;
}
/**
* 设置侧滑功能开关
*
* @param swipeEnable
*/
public void setSwipeEnable(boolean swipeEnable) {
isSwipeEnable = swipeEnable;
}
public boolean isIos() {
return isIos;
}
/**
* 设置是否开启IOS阻塞式交互
*
* @param ios
*/
public SwipeMenuViewGroup setIos(boolean ios) {
isIos = ios;
return this;
}
public boolean isLeftSwipe() {
return isLeftSwipe;
}
/**
* 设置是否开启左滑出菜单,设置false 为右滑出菜单
*
* @param leftSwipe
* @return
*/
public SwipeMenuViewGroup setLeftSwipe(boolean leftSwipe) {
isLeftSwipe = leftSwipe;
return this;
}
/**
* 返回ViewCache
*
* @return
*/
public static SwipeMenuViewGroup getViewCache() {
return mViewCache;
}
private void init(Context context, AttributeSet attrs, int defStyleAttr) {
mScaleTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
mMaxVelocity = ViewConfiguration.get(context).getScaledMaximumFlingVelocity();
//右滑删除功能的开关,默认开
isSwipeEnable = true;
//IOS、QQ式交互,默认开
isIos = true;
//左滑右滑的开关,默认左滑打开菜单
isLeftSwipe = true;
TypedArray ta = context.getTheme().obtainStyledAttributes(attrs, R.styleable.SwipeMenuViewGroup, defStyleAttr, 0);
int count = ta.getIndexCount();
for (int i = 0; i < count; i++) {
int attr = ta.getIndex(i);
//如果引用成AndroidLib资源都不是常量,无法使用switch case
if (attr == R.styleable.SwipeMenuViewGroup_swipeEnable) {
isSwipeEnable = ta.getBoolean(attr, true);
} else if (attr == R.styleable.SwipeMenuViewGroup_ios) {
isIos = ta.getBoolean(attr, true);
} else if (attr == R.styleable.SwipeMenuViewGroup_leftSwipe) {
isLeftSwipe = ta.getBoolean(attr, true);
}
}
ta.recycle();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setClickable(true);//令自己可点击,从而获取触摸事件
mRightMenuWidths = 0;//由于ViewHolder的复用机制,每次这里要手动恢复初始值
int contentWidth = 0;//适配GridLayoutManager,将以第一个子Item(即ContentItem)的宽度为控件宽度
int childCount = getChildCount();
//为了子View的高,可以matchParent(参考的FrameLayout 和LinearLayout的Horizontal)
final boolean measureMatchParentChildren = MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;
boolean isNeedMeasureChildHeight = false;
for (int i = 0; i < childCount; i++) {
View childView = getChildAt(i);
//令每一个子View可点击,从而获取触摸事件
childView.setClickable(true);
if (childView.getVisibility() != GONE) {
//后续计划加入上滑、下滑,则将不再支持Item的margin
measureChild(childView, widthMeasureSpec, heightMeasureSpec);
final MarginLayoutParams lp = (MarginLayoutParams) childView.getLayoutParams();
mHeight = Math.max(mHeight, childView.getMeasuredHeight());
if (measureMatchParentChildren && lp.height == LayoutParams.MATCH_PARENT) {
isNeedMeasureChildHeight = true;
}
if (i > 0) {//第一个布局是Left item,从第二个开始才是RightMenu
mRightMenuWidths += childView.getMeasuredWidth();
} else {
mContentView = childView;
contentWidth = childView.getMeasuredWidth();
}
}
}
setMeasuredDimension(getPaddingLeft() + getPaddingRight() + contentWidth,
mHeight + getPaddingTop() + getPaddingBottom());//宽度取第一个Item(Content)的宽度
mLimit = mRightMenuWidths * 4 / 10;//滑动判断的临界值
if (isNeedMeasureChildHeight) {//如果子View的height有MatchParent属性的,设置子View高度
forceUniformHeight(childCount, widthMeasureSpec);
}
}
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new MarginLayoutParams(getContext(), attrs);
}
/**
* 给MatchParent的子View设置高度
*
* @param count
* @param widthMeasureSpec
* @see android.widget.LinearLayout# 同名方法
*/
private void forceUniformHeight(int count, int widthMeasureSpec) {
// Pretend that the linear layout has an exact size. This is the measured height of
// ourselves. The measured height should be the max height of the children, changed
// to accommodate the heightMeasureSpec from the parent
int uniformMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(),
MeasureSpec.EXACTLY);//以父布局高度构建一个Exactly的测量参数
for (int i = 0; i < count; ++i) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
if (lp.height == LayoutParams.MATCH_PARENT) {
int oldWidth = lp.width;//measureChildWithMargins 这个函数会用到宽,所以要保存一下
lp.width = child.getMeasuredWidth();
// Remeasure with new dimensions
measureChildWithMargins(child, widthMeasureSpec, 0, uniformMeasureSpec, 0);
lp.width = oldWidth;
}
}
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int childCount = getChildCount();
int left = 0 + getPaddingLeft();
int right = 0 + getPaddingLeft();
for (int i = 0; i < childCount; i++) {
View childView = getChildAt(i);
if (childView.getVisibility() != GONE) {
if (i == 0) {//第一个子View是内容,宽度设置为全屏
childView.layout(left, getPaddingTop(), left + childView.getMeasuredWidth(), getPaddingTop() + childView.getMeasuredHeight());
left = left + childView.getMeasuredWidth();
} else {
if (isLeftSwipe) {
childView.layout(left, getPaddingTop(), left + childView.getMeasuredWidth(), getPaddingTop() + childView.getMeasuredHeight());
left = left + childView.getMeasuredWidth();
} else {
childView.layout(right - childView.getMeasuredWidth(), getPaddingTop(), right, getPaddingTop() + childView.getMeasuredHeight());
right = right - childView.getMeasuredWidth();
}
}
}
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (isSwipeEnable) {
acquireVelocityTracker(ev);
final VelocityTracker verTracker = mVelocityTracker;
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
isUserSwiped = false;//判断手指起始落点,如果距离属于滑动了,就屏蔽一切点击事件
isUnMoved = true;
iosInterceptFlag = false;//每次DOWN时,默认是不拦截的
if (isTouching) {//如果有别的指头摸过了,那么就return false
return false;
} else {
isTouching = true;//第一个摸的指头,赶紧改变标志,宣誓主权
}
mLastP.set(ev.getRawX(), ev.getRawY());
mFirstP.set(ev.getRawX(), ev.getRawY());//判断手指起始落点,如果距离属于滑动了,就屏蔽一切点击事件
//如果down,view和cacheview不一样,则立马让它还原。且把它置为null
if (mViewCache != null) {
if (mViewCache != this) {
mViewCache.smoothClose();
iosInterceptFlag = isIos;//IOS模式开启的话,且当前有侧滑菜单的View,且不是自己的,就拦截该事件
}
//只要有一个侧滑菜单处于打开状态, 就不给外层布局上下滑动了
getParent().requestDisallowInterceptTouchEvent(true);
}
//求第一个触点的id, 此时可能有多个触点,但至少一个,计算滑动速率用
mPointerId = ev.getPointerId(0);
break;
case MotionEvent.ACTION_MOVE:
//IOS模式开启的话,且当前有侧滑菜单的View,且不是自己的,就该拦截事件咯。滑动也不该出现
if (iosInterceptFlag) {
break;
}
float gap = mLastP.x - ev.getRawX();
//为了在水平滑动中禁止父类ListView等再竖直滑动
if (Math.abs(gap) > 10 || Math.abs(getScrollX()) > 10) {//修改此处,使屏蔽父布局滑动更加灵敏
getParent().requestDisallowInterceptTouchEvent(true);
}
if (Math.abs(gap) > mScaleTouchSlop) {
isUnMoved = false;
}
scrollBy((int) (gap), 0);//滑动使用scrollBy
//越界修正
if (isLeftSwipe) {//左滑
if (getScrollX() < 0) {
scrollTo(0, 0);
}
if (getScrollX() > mRightMenuWidths) {
scrollTo(mRightMenuWidths, 0);
}
} else {//右滑
if (getScrollX() < -mRightMenuWidths) {
scrollTo(-mRightMenuWidths, 0);
}
if (getScrollX() > 0) {
scrollTo(0, 0);
}
}
mLastP.set(ev.getRawX(), ev.getRawY());
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (Math.abs(ev.getRawX() - mFirstP.x) > mScaleTouchSlop) {
isUserSwiped = true;
}
if (!iosInterceptFlag ) {//且滑动了 才判断是否要收起、展开menu
//求伪瞬时速度
verTracker.computeCurrentVelocity(1000, mMaxVelocity);
final float velocityX = verTracker.getXVelocity(mPointerId);
if (Math.abs(velocityX) > 1000) {//滑动速度超过阈值
if (velocityX < -1000) {
if (isLeftSwipe) {//左滑
//平滑展开Menu
smoothExpand();
} else {
//平滑关闭Menu
smoothClose();
}
} else {
if (isLeftSwipe) {//左滑
// 平滑关闭Menu
smoothClose();
} else {
//平滑展开Menu
smoothExpand();
}
}
} else {
if (Math.abs(getScrollX()) > mLimit) {//否则就判断滑动距离
//平滑展开Menu
smoothExpand();
} else {
// 平滑关闭Menu
smoothClose();
}
}
}
//释放
releaseVelocityTracker();
isTouching = false;
break;
default:
break;
}
}
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
// fix 长按事件和侧滑的冲突
case MotionEvent.ACTION_MOVE:
//屏蔽滑动时的事件
if (Math.abs(ev.getRawX() - mFirstP.x) > mScaleTouchSlop) {
return true;
}
break;
case MotionEvent.ACTION_UP:
//为了在侧滑时,屏蔽子View的点击事件
if (isLeftSwipe) {
if (getScrollX() > mScaleTouchSlop) {
if (ev.getX() < getWidth() - getScrollX()) {
if (isUnMoved) {
smoothClose();
}
return true;//true表示拦截
}
}
} else {
if (-getScrollX() > mScaleTouchSlop) {
if (ev.getX() > -getScrollX()) {//点击范围在菜单外则屏蔽
if (isUnMoved) {
smoothClose();
}
return true;
}
}
}
if (isUserSwiped) {
return true;
}
break;
}
//模仿IOS 点击其他区域关闭
if (iosInterceptFlag) {
//IOS模式开启,且当前有菜单的View,且不是自己的 拦截点击事件给子View
return true;
}
return super.onInterceptTouchEvent(ev);
}
/**
* 平滑展开
*/
private ValueAnimator mExpandAnim, mCloseAnim;
private boolean isExpand;//代表当前是否是展开状态
public void smoothExpand() {
//展开就加入ViewCache:
mViewCache = SwipeMenuViewGroup.this;
//侧滑菜单展开,屏蔽content长按
if (null != mContentView) {
mContentView.setLongClickable(false);
}
if (mCloseAnim != null && mCloseAnim.isRunning()) {
mCloseAnim.cancel();
}
mExpandAnim = ValueAnimator.ofInt(getScrollX(), isLeftSwipe ? mRightMenuWidths : -mRightMenuWidths);
mExpandAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
scrollTo((Integer) animation.getAnimatedValue(), 0);
}
});
mExpandAnim.setInterpolator(new OvershootInterpolator());
mExpandAnim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
isExpand = true;
}
});
mExpandAnim.setDuration(300).start();
}
/**
* 平滑关闭
*/
public void smoothClose() {
mViewCache = null;
if (null != mContentView) {
mContentView.setLongClickable(true);
}
if (mExpandAnim != null && mExpandAnim.isRunning()) {
mExpandAnim.cancel();
}
mCloseAnim = ValueAnimator.ofInt(getScrollX(), 0);
mCloseAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
scrollTo((Integer) animation.getAnimatedValue(), 0);
}
});
mCloseAnim.setInterpolator(new AccelerateInterpolator());
mCloseAnim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
isExpand = false;
}
});
mCloseAnim.setDuration(300).start();
}
/**
* @param event 向VelocityTracker添加MotionEvent
* @see VelocityTracker#obtain()
* @see VelocityTracker#addMovement(MotionEvent)
*/
private void acquireVelocityTracker(final MotionEvent event) {
if (null == mVelocityTracker) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(event);
}
/**
* * 释放VelocityTracker
*
* @see VelocityTracker#clear()
* @see VelocityTracker#recycle()
*/
private void releaseVelocityTracker() {
if (null != mVelocityTracker) {
mVelocityTracker.clear();
mVelocityTracker.recycle();
mVelocityTracker = null;
}
}
@Override
protected void onDetachedFromWindow() {
if (this == mViewCache) {
mViewCache.smoothClose();
mViewCache = null;
}
super.onDetachedFromWindow();
}
//展开时,禁止长按
@Override
public boolean performLongClick() {
if (Math.abs(getScrollX()) > mScaleTouchSlop) {
return false;
}
return super.performLongClick();
}
/**
* 快速关闭
* 用于点击侧滑菜单上的选项,同时想让它快速关闭(删除 编辑)
* 这个方法在ListView里是必须调用的
* 在RecyclerView里视情况而定,如果是mAdapter.notifyItemRemoved(pos)方法则不用调用
*/
public void quickClose() {
if (this == mViewCache) {
//先取消展开动画
if (null != mExpandAnim && mExpandAnim.isRunning()) {
mExpandAnim.cancel();
}
mViewCache.scrollTo(0, 0);//关闭
mViewCache = null;
}
}
}
<com.john.sideslipdemo.SwipeMenuViewGroup
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="64dp"
android:paddingBottom="1dp"
app:ios="false"
app:leftSwipe="true"
app:swipeEnable="true"
android:clickable="true">
<LinearLayout
android:id="@+id/content_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
android:gravity="center_vertical"
android:orientation="horizontal"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<ImageView
android:id="@+id/content_iv"
android:layout_width="40dp"
android:layout_height="40dp"
tools:src="@drawable/ic_more"/>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="12dp"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="@+id/content_tv"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:textColor="@android:color/black"
android:textSize="15sp"
tools:text="测试"/>
<TextView
android:id="@+id/time_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:text="10:00"
android:textColor="@android:color/darker_gray"
android:textSize="13sp"/>
LinearLayout>
LinearLayout>
<LinearLayout
android:layout_width="160dp"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:background="#76828F"
android:orientation="horizontal"
android:clickable="true">
<ImageView
android:id="@+id/iv_delete"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="@drawable/swipe_more_delete" />
<ImageView
android:id="@+id/iv_edit"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="@drawable/swipe_more_edit" />
LinearLayout>
com.john.sideslipdemo.SwipeMenuViewGroup>
使用setSwipeEnable方法
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = inflater.inflate(R.layout.list_item, parent, false);
viewHolder.rootView = (SwipeMenuViewGroup) convertView;
viewHolder.rootView.setSwipeEnable(true);
viewHolder.contentView = (LinearLayout) convertView.findViewById(R.id.content_view);
viewHolder.contentTv = (TextView) convertView.findViewById(R.id.content_tv);
viewHolder.contentIv = (ImageView) convertView.findViewById(R.id.content_iv);
viewHolder.deleteIv = (ImageView) convertView.findViewById(R.id.iv_delete);
viewHolder.editIv = (ImageView) convertView.findViewById(R.id.iv_edit);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
if(position % 2 == 0) {
viewHolder.rootView.setSwipeEnable(false);
}
viewHolder.contentTv.setText(mList.get(position));
viewHolder.contentIv.setImageResource(R.drawable.ic_more);
return convertView;
}
因为这个侧滑效果思路的实现只需要编写一个类完成,所以没有把他作为开源库,使用时直接将这个类拷贝到自己的工程中即可。
http://download.csdn.net/download/johnwcheung/9936745
修复点为SwipeMenuViewGroup的dispatchTouchEvent,此中新增处理不可滑动的情况:
if (isSwipeEnable) {
......
} else {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
//如果down,view和cacheview不一样,则立马让它还原。且把它置为null
if (mViewCache != null) {
if (mViewCache != this) {
mViewCache.smoothClose();
}
//只要有一个侧滑菜单处于打开状态, 就不给外层布局上下滑动了
getParent().requestDisallowInterceptTouchEvent(true);
}
break;
default:
break;
}
}