功能:在listview上,向右滑动,直接删除一个item
主要实现思路:
检测listview的touch操作,down时,记录位置,up时,做删除。
部分代码:
mListView.setOnTouchListener(new OnTouchListener() { private int mDownX = 0; private int mDownY = 0; @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mDownX = Math.round(event.getX()); mDownY = Math.round(event.getY()); break; case MotionEvent.ACTION_MOVE: break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: { int upX = Math.round(event.getX()); int upY = Math.round(event.getY()); // 获取2次点击的item位置 item以外的pos是-1 int downPosition = ((ListView)v).pointToPosition(mDownX, mDownY); int upPosition = ((ListView)v).pointToPosition(upX, upY); // 2次都在同一个item内 且有50的滑动距离 if (downPosition == upPosition && (upX - mDownX) > 20) { // 如果没在动画中 且 点击在有效item内 才做处理 boolean willRemove = (!mIsRemoving) && (upPosition >= 0); if (willRemove) { // 做删除动作 先动画 然后动画结束后做删除 // 需要先获取第一个可见的view 因为getChildAt获取view的时候,坐标是从第一个可见view开始的 int firstVisiableIndex = ((ListView)v).getFirstVisiblePosition(); final int positionToRemove = upPosition; View viewToRemove = ((ListView)v).getChildAt(upPosition - firstVisiableIndex); // 移除动画 移动+渐隐 Animation transAni = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0); Animation alphaAni = new AlphaAnimation(1.0f, 0); AnimationSet removeAni = new AnimationSet(true); removeAni.addAnimation(transAni); removeAni.addAnimation(alphaAni); removeAni.setDuration(500); // 设置回调 在动画结束后做删除数据 removeAni.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) { mIsRemoving = true; } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { // 结束时删除数据 // 删除外面的数据 mAdapter.removeData(positionToRemove); // animation.cancel(); // 调用cancel会导致二次进入onAnimationEnd mIsRemoving = false; } }); // 加入动画 viewToRemove.startAnimation(removeAni); } } } break; default: break; } return false; } });
// 处理掉item点击高亮 同时也导致item的click和longclick无法响应 @Override public boolean areAllItemsEnabled() { return false; } @Override public boolean isEnabled(int position) { return false; }
效果: