左右滑動刪除 ListView 條目:第三方開源框架 SwipeToDismiss

Android 的 SwipeToDismiss 是 GitHub 上一個第三方開源框架(專案連結:https://github.com/romannurik/Android-SwipeToDismiss )。該開源專案旨在:讓 ListView 的 item 在使用者手指左滑或右滑時,刪除當前的 ListView Item。
下載後只需找到其中的 SwipeDismissListViewTouchListener.java 類別,複製貼上到需要的套件中即可:

![]()
1 /* 2 * Copyright 2013 Google Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * https://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.zzw.testswipetodismiss; 18 19 import android.animation.Animator; 20 import android.animation.AnimatorListenerAdapter; 21 import android.animation.ValueAnimator; 22 import android.graphics.Rect; 23 import android.os.SystemClock; 24 import android.view.MotionEvent; 25 import android.view.VelocityTracker; 26 import android.view.View; 27 import android.view.ViewConfiguration; 28 import android.view.ViewGroup; 29 import android.view.ViewPropertyAnimator; 30 import android.widget.AbsListView; 31 import android.widget.ListView; 32 33 import java.util.ArrayList; 34 import java.util.Collections; 35 import java.util.List; 36 37 /** 38 * A {@link View.OnTouchListener} that makes the list items in a {@link ListView} 39 * dismissable. {@link ListView} is given special treatment because by default it handles touches 40 * for its list items... i.e. it's in charge of drawing the pressed state (the list selector), 41 * handling list item clicks, etc. 42 * 43 * <p>After creating the listener, the caller should also call 44 * {@link ListView#setOnScrollListener(AbsListView.OnScrollListener)}, passing 45 * in the scroll listener returned by {@link #makeScrollListener()}. If a scroll listener is 46 * already assigned, the caller should still pass scroll changes through to this listener. This will 47 * ensure that this {@link SwipeDismissListViewTouchListener} is paused during list view 48 * scrolling.</p> 49 * 50 * <p>Example usage:</p> 51 * 52 * <pre> 53 * SwipeDismissListViewTouchListener touchListener = 54 * new SwipeDismissListViewTouchListener( 55 * listView, 56 * new SwipeDismissListViewTouchListener.OnDismissCallback() { 57 * public void onDismiss(ListView listView, int[] reverseSortedPositions) { 58 * for (int position : reverseSortedPositions) { 59 * adapter.remove(adapter.getItem(position)); 60 * } 61 * adapter.notifyDataSetChanged(); 62 * } 63 * }); 64 * listView.setOnTouchListener(touchListener); 65 * listView.setOnScrollListener(touchListener.makeScrollListener()); 66 * </pre> 67 * 68 * <p>This class Requires API level 12 or later due to use of {@link 69 * ViewPropertyAnimator}.</p> 70 * 71 * <p>For a generalized {@link View.OnTouchListener} that makes any view dismissable, 72 * see {@link SwipeDismissTouchListener}.</p> 73 * 74 * @see SwipeDismissTouchListener 75 */ 76 public class SwipeDismissListViewTouchListener implements View.OnTouchListener { 77 // Cached ViewConfiguration and system-wide constant values 78 private int mSlop; 79 private int mMinFlingVelocity; 80 private int mMaxFlingVelocity; 81 private long mAnimationTime; 82 83 // Fixed properties 84 private ListView mListView; 85 private DismissCallbacks mCallbacks; 86 private int mViewWidth = 1; // 1 and not 0 to prevent dividing by zero 87 88 // Transient properties 89 private List<PendingDismissData> mPendingDismisses = new ArrayList<PendingDismissData>(); 90 private int mDismissAnimationRefCount = 0; 91 private float mDownX; 92 private float mDownY; 93 private boolean mSwiping; 94 private int mSwipingSlop; 95 private VelocityTracker mVelocityTracker; 96 private int mDownPosition; 97 private View mDownView; 98 private boolean mPaused; 99 100 /** 101 * The callback interface used by {@link SwipeDismissListViewTouchListener} to inform its client 102 * about a successful dismissal of one or more list item positions. 103 */ 104 public interface DismissCallbacks { 105 /** 106 * Called to determine whether the given position can be dismissed. 107 */ 108 boolean canDismiss(int position); 109 110 /** 111 * Called when the user has indicated they she would like to dismiss one or more list item 112 * positions. 113 * 114 * @param listView The originating {@link ListView}. 115 * @param reverseSortedPositions An array of positions to dismiss, sorted in descending 116 * order for convenience. 117 */ 118 void onDismiss(ListView listView, int[] reverseSortedPositions); 119 } 120 121 /** 122 * Constructs a new swipe-to-dismiss touch listener for the given list view. 123 * 124 * @param listView The list view whose items should be dismissable. 125 * @param callbacks The callback to trigger when the user has indicated that she would like to 126 * dismiss one or more list items. 127 */ 128 public SwipeDismissListViewTouchListener(ListView listView, DismissCallbacks callbacks) { 129 ViewConfiguration vc = ViewConfiguration.get(listView.getContext()); 130 mSlop = vc.getScaledTouchSlop(); 131 mMinFlingVelocity = vc.getScaledMinimumFlingVelocity() * 16; 132 mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity(); 133 mAnimationTime = listView.getContext().getResources().getInteger( 134 android.R.integer.config_shortAnimTime); 135 mListView = listView; 136 mCallbacks = callbacks; 137 } 138 139 /** 140 * Enables or disables (pauses or resumes) watching for swipe-to-dismiss gestures. 141 * 142 * @param enabled Whether or not to watch for gestures. 143 */ 144 public void setEnabled(boolean enabled) { 145 mPaused = !enabled; 146 } 147 148 /** 149 * Returns an {@link AbsListView.OnScrollListener} to be added to the {@link 150 * ListView} using {@link ListView#setOnScrollListener(AbsListView.OnScrollListener)}. 151 * If a scroll listener is already assigned, the caller should still pass scroll changes through 152 * to this listener. This will ensure that this {@link SwipeDismissListViewTouchListener} is 153 * paused during list view scrolling.</p> 154 * 155 * @see SwipeDismissListViewTouchListener 156 */ 157 public AbsListView.OnScrollListener makeScrollListener() { 158 return new AbsListView.OnScrollListener() { 159 @Override 160 public void onScrollStateChanged(AbsListView absListView, int scrollState) { 161 setEnabled(scrollState != AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL); 162 } 163 164 @Override 165 public void onScroll(AbsListView absListView, int i, int i1, int i2) { 166 } 167 }; 168 } 169 170 @Override 171 public boolean onTouch(View view, MotionEvent motionEvent) { 172 if (mViewWidth < 2) { 173 mViewWidth = mListView.getWidth(); 174 } 175 176 switch (motionEvent.getActionMasked()) { 177 case MotionEvent.ACTION_DOWN: { 178 if (mPaused) { 179 return false; 180 } 181 182 // TODO: ensure this is a finger, and set a flag 183 // Find the child view that was touched (perform a hit test) 184 Rect rect = new Rect(); 185 int childCount = mListView.getChildCount(); 186 int[] listViewCoords = new int[2]; 187 mListView.getLocationOnScreen(listViewCoords); 188 int x = (int) motionEvent.getRawX() - listViewCoords[0]; 189 int y = (int) motionEvent.getRawY() - listViewCoords[1]; 190 View child; 191 for (int i = 0; i < childCount; i++) { 192 child = mListView.getChildAt(i); 193 child.getHitRect(rect); 194 if (rect.contains(x, y)) { 195 mDownView = child; 196 break; 197 } 198 } 199 200 if (mDownView != null) { 201 mDownX = motionEvent.getRawX(); 202 mDownY = motionEvent.getRawY(); 203 mDownPosition = mListView.getPositionForView(mDownView); 204 if (mCallbacks.canDismiss(mDownPosition)) { 205 mVelocityTracker = VelocityTracker.obtain(); 206 mVelocityTracker.addMovement(motionEvent); 207 } else { 208 mDownView = null; 209 } 210 } 211 return false; 212 } 213 214 case MotionEvent.ACTION_CANCEL: { 215 if (mVelocityTracker == null) { 216 break; 217 } 218 219 if (mDownView != null && mSwiping) { 220 // cancel 221 mDownView.animate() 222 .translationX(0) 223 .alpha(1) 224 .setDuration(mAnimationTime) 225 .setListener(null); 226 } 227 mVelocityTracker.recycle(); 228 mVelocityTracker = null; 229 mDownX = 0; 230 mDownY = 0; 231 mDownView = null; 232 mDownPosition = ListView.INVALID_POSITION; 233 mSwiping = false; 234 break; 235 } 236 237 case MotionEvent.ACTION_UP: { 238 if (mVelocityTracker == null) { 239 break; 240 } 241 float deltaX = motionEvent.getRawX() - mDownX; 242 mVelocityTracker.addMovement(motionEvent); 243 mVelocityTracker.computeCurrentVelocity(1000); 244 float velocityX = mVelocityTracker.getXVelocity(); 245 float absVelocityX = Math.abs(velocityX); 246 float absVelocityY = Math.abs(mVelocityTracker.getYVelocity()); 247 boolean dismiss = false; 248 boolean dismissRight = false; 249 if (Math.abs(deltaX) > mViewWidth / 2 && mSwiping) { 250 dismiss = true; 251 dismissRight = deltaX > 0; 252 } else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity 253 && absVelocityY < absVelocityX && mSwiping) { 254 // dismiss only if flinging in the same direction as dragging 255 dismiss = (velocityX < 0) == (deltaX < 0); 256 dismissRight = mVelocityTracker.getXVelocity() > 0; 257 } 258 if (dismiss && mDownPosition != ListView.INVALID_POSITION) { 259 // dismiss 260 final View downView = mDownView; // mDownView gets null'd before animation ends 261 final int downPosition = mDownPosition; 262 ++mDismissAnimationRefCount; 263 mDownView.animate() 264 .translationX(dismissRight ? mViewWidth : -mViewWidth) 265 .alpha(0) 266 .setDuration(mAnimationTime) 267 .setListener(new AnimatorListenerAdapter() { 268 @Override 269 public void onAnimationEnd(Animator animation) { 270 performDismiss(downView, downPosition); 271 } 272 }); 273 } else { 274 // cancel 275 mDownView.animate() 276 .translationX(0) 277 .alpha(1) 278 .setDuration(mAnimationTime) 279 .setListener(null); 280 } 281 mVelocityTracker.recycle(); 282 mVelocityTracker = null; 283 mDownX = 0; 284 mDownY = 0; 285 mDownView = null; 286 mDownPosition = ListView.INVALID_POSITION; 287 mSwiping = false; 288 break; 289 } 290 291 case MotionEvent.ACTION_MOVE: { 292 if (mVelocityTracker == null || mPaused) { 293 break; 294 } 295 mVelocityTracker.addMovement(motionEvent); 296 float deltaX = motionEvent.getRawX() - mDownX; 297 float deltaY = motionEvent.getRawY() - mDownY; 298 if (Math.abs(deltaX) > mSlop && Math.abs(deltaY) < Math.abs(deltaX) / 2) { 299 mSwiping = true; 300 mSwipingSlop = (deltaX > 0 ? mSlop : -mSlop); 301 mListView.requestDisallowInterceptTouchEvent(true); 302 303 // Cancel ListView's touch (un-highlighting the item) 304 MotionEvent cancelEvent = MotionEvent.obtain(motionEvent); 305 cancelEvent.setAction(MotionEvent.ACTION_CANCEL | 306 (motionEvent.getActionIndex() 307 << MotionEvent.ACTION_POINTER_INDEX_SHIFT)); 308 mListView.onTouchEvent(cancelEvent); 309 cancelEvent.recycle(); 310 } 311 312 if (mSwiping) { 313 mDownView.setTranslationX(deltaX - mSwipingSlop); 314 mDownView.setAlpha(Math.max(0f, Math.min(1f, 315 1f - 2f * Math.abs(deltaX) / mViewWidth))); 316 return true; 317 } 318 break; 319 } 320 } 321 return false; 322 } 323 324 class PendingDismissData implements Comparable<PendingDismissData> { 325 public int position; 326 public View view; 327 328 public PendingDismissData(int position, View view) { 329 this.position = position; 330 this.view = view; 331 } 332 333 @Override 334 public int compareTo(PendingDismissData other) { 335 // Sort by descending position 336 return other.position - position; 337 } 338 } 339 340 private void performDismiss(final View dismissView, final int dismissPosition) { 341 // Animate the dismissed list item to zero-height and fire the dismiss callback when 342 // all dismissed list item animations have completed. This triggers layout on each animation 343 // frame; in the future we may want to do something smarter and more performant. 344 345 final ViewGroup.LayoutParams lp = dismissView.getLayoutParams(); 346 final int originalHeight = dismissView.getHeight(); 347 348 ValueAnimator animator = ValueAnimator.ofInt(originalHeight, 1).setDuration(mAnimationTime); 349 350 animator.addListener(new AnimatorListenerAdapter() { 351 @Override 352 public void onAnimationEnd(Animator animation) { 353 --mDismissAnimationRefCount; 354 if (mDismissAnimationRefCount == 0) { 355 // No active animations, process all pending dismisses. 356 // Sort by descending position 357 Collections.sort(mPendingDismisses); 358 359 int[] dismissPositions = new int[mPendingDismisses.size()]; 360 for (int i = mPendingDismisses.size() - 1; i >= 0; i--) { 361 dismissPositions[i] = mPendingDismisses.get(i).position; 362 } 363 mCallbacks.onDismiss(mListView, dismissPositions); 364 365 // Reset mDownPosition to avoid MotionEvent.ACTION_UP trying to start a dismiss 366 // animation with a stale position 367 mDownPosition = ListView.INVALID_POSITION; 368 369 ViewGroup.LayoutParams lp; 370 for (PendingDismissData pendingDismiss : mPendingDismisses) { 371 // Reset view presentation 372 pendingDismiss.view.setAlpha(1f); 373 pendingDismiss.view.setTranslationX(0); 374 lp = pendingDismiss.view.getLayoutParams(); 375 lp.height = originalHeight; 376 pendingDismiss.view.setLayoutParams(lp); 377 } 378 379 // Send a cancel event 380 long time = SystemClock.uptimeMillis(); 381 MotionEvent cancelEvent = MotionEvent.obtain(time, time, 382 MotionEvent.ACTION_CANCEL, 0, 0, 0); 383 mListView.dispatchTouchEvent(cancelEvent); 384 385 mPendingDismisses.clear(); 386 } 387 } 388 }); 389 390 animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { 391 @Override 392 public void onAnimationUpdate(ValueAnimator valueAnimator) { 393 lp.height = (Integer) valueAnimator.getAnimatedValue(); 394 dismissView.setLayoutParams(lp); 395 } 396 }); 397 398 mPendingDismisses.add(new PendingDismissData(dismissPosition, dismissView)); 399 animator.start(); 400 } 401 }
以下是測試用的程式碼。
activity_main.xml:

![]()
1 <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" 2 xmlns:tools="https://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" > 5 6 <ListView 7 android:id="@+id/listView" 8 android:layout_width="match_parent" 9 android:layout_height="match_parent" /> 10 11 </RelativeLayout> activity_main.xml
MainActivity.java:
1 package com.zzw.testswipetodismiss; 2 3 import java.util.ArrayList; 4 5 import android.app.Activity; 6 import android.os.Bundle; 7 import android.widget.ArrayAdapter; 8 import android.widget.ListView; 9 import android.widget.Toast; 10 11 public class MainActivity extends Activity { 12 13 private ListView listView; 14 private ArrayList<String> datas; 15 private ArrayAdapter adapter; 16 17 @Override 18 protected void onCreate(Bundle savedInstanceState) { 19 super.onCreate(savedInstanceState); 20 setContentView(R.layout.activity_main); 21 22 datas = new ArrayList<String>(); 23 24 // 添加測試數據 25 for (int i = 0; i <= 50; i++) { 26 datas.add("測試數據-->" + i); 27 } 28 29 listView = (ListView) findViewById(R.id.listView); 30 31 adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, datas); 32 listView.setAdapter(adapter); 33 34 // 將ListView傳遞過來。 35 SwipeDismissListViewTouchListener touchListener = new SwipeDismissListViewTouchListener(listView, 36 new SwipeDismissListViewTouchListener.DismissCallbacks() { 37 38 // 此處將執行刪除,記得要notifyDataSetChanged() 39 @Override 40 public void onDismiss(ListView listView, int[] reverseSortedPositions) { 41 for (int pos : reverseSortedPositions) { 42 datas.remove(pos); 43 Toast.makeText(getApplicationContext(), "數據" + pos + "刪除成功", 0).show(); 44 } 45 adapter.notifyDataSetChanged(); 46 } 47 48 @Override 49 public boolean canDismiss(int position) { 50 51 return true; 52 } 53 }); 54 55 listView.setOnTouchListener(touchListener); 56 } 57 58 }