BaseRecyclerViewInstrumentationTest.java revision 5321949b1ca4113d9ebd5ca488a27f17224118a1
1/* 2 * Copyright (C) 2014 The Android Open Source Project 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 * http://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 17package android.support.v7.widget; 18 19import android.app.Instrumentation; 20import android.graphics.Rect; 21import android.os.Handler; 22import android.os.Looper; 23import android.support.v4.view.ViewCompat; 24import android.test.ActivityInstrumentationTestCase2; 25import android.util.Log; 26import android.view.LayoutInflater; 27import android.view.View; 28import android.view.ViewGroup; 29import android.widget.FrameLayout; 30import android.widget.TextView; 31 32import java.lang.reflect.InvocationTargetException; 33import java.lang.reflect.Method; 34import java.util.ArrayList; 35import java.util.HashSet; 36import java.util.List; 37import java.util.Set; 38import java.util.concurrent.CountDownLatch; 39import java.util.concurrent.TimeUnit; 40import java.util.concurrent.atomic.AtomicInteger; 41import java.util.concurrent.locks.ReentrantLock; 42import android.support.v7.recyclerview.test.R; 43 44abstract public class BaseRecyclerViewInstrumentationTest extends 45 ActivityInstrumentationTestCase2<TestActivity> { 46 47 private static final String TAG = "RecyclerViewTest"; 48 49 private boolean mDebug; 50 51 protected RecyclerView mRecyclerView; 52 53 protected AdapterHelper mAdapterHelper; 54 55 Throwable mainThreadException; 56 57 Thread mInstrumentationThread; 58 59 public BaseRecyclerViewInstrumentationTest() { 60 this(false); 61 } 62 63 public BaseRecyclerViewInstrumentationTest(boolean debug) { 64 super("android.support.v7.recyclerview", TestActivity.class); 65 mDebug = debug; 66 } 67 68 void checkForMainThreadException() throws Throwable { 69 if (mainThreadException != null) { 70 throw mainThreadException; 71 } 72 } 73 74 @Override 75 protected void setUp() throws Exception { 76 super.setUp(); 77 mInstrumentationThread = Thread.currentThread(); 78 } 79 80 void setHasTransientState(final View view, final boolean value) { 81 try { 82 runTestOnUiThread(new Runnable() { 83 @Override 84 public void run() { 85 ViewCompat.setHasTransientState(view, value); 86 } 87 }); 88 } catch (Throwable throwable) { 89 Log.e(TAG, "", throwable); 90 } 91 } 92 93 protected void enableAccessibility() 94 throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { 95 Method getUIAutomation = Instrumentation.class.getMethod("getUiAutomation"); 96 getUIAutomation.invoke(getInstrumentation()); 97 } 98 99 void setAdapter(final RecyclerView.Adapter adapter) throws Throwable { 100 runTestOnUiThread(new Runnable() { 101 @Override 102 public void run() { 103 mRecyclerView.setAdapter(adapter); 104 } 105 }); 106 } 107 108 protected WrappedRecyclerView inflateWrappedRV() { 109 return (WrappedRecyclerView) 110 LayoutInflater.from(getActivity()).inflate(R.layout.wrapped_test_rv, 111 getRecyclerViewContainer(), false); 112 } 113 114 void swapAdapter(final RecyclerView.Adapter adapter, 115 final boolean removeAndRecycleExistingViews) throws Throwable { 116 runTestOnUiThread(new Runnable() { 117 @Override 118 public void run() { 119 try { 120 mRecyclerView.swapAdapter(adapter, removeAndRecycleExistingViews); 121 } catch (Throwable t) { 122 postExceptionToInstrumentation(t); 123 } 124 } 125 }); 126 checkForMainThreadException(); 127 } 128 129 void postExceptionToInstrumentation(Throwable t) { 130 if (mInstrumentationThread == Thread.currentThread()) { 131 throw new RuntimeException(t); 132 } 133 if (mainThreadException != null) { 134 Log.e(TAG, "receiving another main thread exception. dropping.", t); 135 } else { 136 Log.e(TAG, "captured exception on main thread", t); 137 mainThreadException = t; 138 } 139 140 if (mRecyclerView != null && mRecyclerView 141 .getLayoutManager() instanceof TestLayoutManager) { 142 TestLayoutManager lm = (TestLayoutManager) mRecyclerView.getLayoutManager(); 143 // finish all layouts so that we get the correct exception 144 while (lm.layoutLatch.getCount() > 0) { 145 lm.layoutLatch.countDown(); 146 } 147 } 148 } 149 150 @Override 151 protected void tearDown() throws Exception { 152 if (mRecyclerView != null) { 153 try { 154 removeRecyclerView(); 155 } catch (Throwable throwable) { 156 throwable.printStackTrace(); 157 } 158 } 159 getInstrumentation().waitForIdleSync(); 160 super.tearDown(); 161 162 try { 163 checkForMainThreadException(); 164 } catch (Exception e) { 165 throw e; 166 } catch (Throwable throwable) { 167 throw new Exception(throwable); 168 } 169 } 170 171 public Rect getDecoratedRecyclerViewBounds() { 172 return new Rect( 173 mRecyclerView.getPaddingLeft(), 174 mRecyclerView.getPaddingTop(), 175 mRecyclerView.getWidth() - mRecyclerView.getPaddingRight(), 176 mRecyclerView.getHeight() - mRecyclerView.getPaddingBottom() 177 ); 178 } 179 180 public void removeRecyclerView() throws Throwable { 181 if (mRecyclerView == null) { 182 return; 183 } 184 if (!isMainThread()) { 185 getInstrumentation().waitForIdleSync(); 186 } 187 runTestOnUiThread(new Runnable() { 188 @Override 189 public void run() { 190 try { 191 final RecyclerView.Adapter adapter = mRecyclerView.getAdapter(); 192 if (adapter instanceof AttachDetachCountingAdapter) { 193 ((AttachDetachCountingAdapter) adapter).getCounter() 194 .validateRemaining(mRecyclerView); 195 } 196 getActivity().mContainer.removeAllViews(); 197 } catch (Throwable t) { 198 postExceptionToInstrumentation(t); 199 } 200 } 201 }); 202 mRecyclerView = null; 203 } 204 205 void waitForAnimations(int seconds) throws InterruptedException { 206 final CountDownLatch latch = new CountDownLatch(2); 207 boolean running = mRecyclerView.mItemAnimator 208 .isRunning(new RecyclerView.ItemAnimator.ItemAnimatorFinishedListener() { 209 @Override 210 public void onAnimationsFinished() { 211 latch.countDown(); 212 } 213 }); 214 if (running) { 215 latch.countDown(); 216 latch.await(seconds, TimeUnit.SECONDS); 217 } 218 } 219 220 public boolean requestFocus(final View view) { 221 final boolean[] result = new boolean[1]; 222 getActivity().runOnUiThread(new Runnable() { 223 @Override 224 public void run() { 225 result[0] = view.requestFocus(); 226 } 227 }); 228 return result[0]; 229 } 230 231 public void setRecyclerView(final RecyclerView recyclerView) throws Throwable { 232 setRecyclerView(recyclerView, true); 233 } 234 public void setRecyclerView(final RecyclerView recyclerView, boolean assignDummyPool) 235 throws Throwable { 236 setRecyclerView(recyclerView, assignDummyPool, true); 237 } 238 public void setRecyclerView(final RecyclerView recyclerView, boolean assignDummyPool, 239 boolean addPositionCheckItemAnimator) 240 throws Throwable { 241 mRecyclerView = recyclerView; 242 if (assignDummyPool) { 243 RecyclerView.RecycledViewPool pool = new RecyclerView.RecycledViewPool() { 244 @Override 245 public RecyclerView.ViewHolder getRecycledView(int viewType) { 246 RecyclerView.ViewHolder viewHolder = super.getRecycledView(viewType); 247 if (viewHolder == null) { 248 return null; 249 } 250 viewHolder.addFlags(RecyclerView.ViewHolder.FLAG_BOUND); 251 viewHolder.mPosition = 200; 252 viewHolder.mOldPosition = 300; 253 viewHolder.mPreLayoutPosition = 500; 254 return viewHolder; 255 } 256 257 @Override 258 public void putRecycledView(RecyclerView.ViewHolder scrap) { 259 assertNull(scrap.mOwnerRecyclerView); 260 super.putRecycledView(scrap); 261 } 262 }; 263 mRecyclerView.setRecycledViewPool(pool); 264 } 265 if (addPositionCheckItemAnimator) { 266 mRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() { 267 @Override 268 public void getItemOffsets(Rect outRect, View view, RecyclerView parent, 269 RecyclerView.State state) { 270 RecyclerView.ViewHolder vh = parent.getChildViewHolder(view); 271 if (!vh.isRemoved()) { 272 assertNotSame("If getItemOffsets is called, child should have a valid" 273 + " adapter position unless it is removed : " + vh, 274 vh.getAdapterPosition(), RecyclerView.NO_POSITION); 275 } 276 } 277 }); 278 } 279 mAdapterHelper = recyclerView.mAdapterHelper; 280 runTestOnUiThread(new Runnable() { 281 @Override 282 public void run() { 283 getActivity().mContainer.addView(recyclerView); 284 } 285 }); 286 } 287 288 protected FrameLayout getRecyclerViewContainer() { 289 return getActivity().mContainer; 290 } 291 292 public void requestLayoutOnUIThread(final View view) { 293 try { 294 runTestOnUiThread(new Runnable() { 295 @Override 296 public void run() { 297 view.requestLayout(); 298 } 299 }); 300 } catch (Throwable throwable) { 301 Log.e(TAG, "", throwable); 302 } 303 } 304 305 public void scrollBy(final int dt) { 306 try { 307 runTestOnUiThread(new Runnable() { 308 @Override 309 public void run() { 310 if (mRecyclerView.getLayoutManager().canScrollHorizontally()) { 311 mRecyclerView.scrollBy(dt, 0); 312 } else { 313 mRecyclerView.scrollBy(0, dt); 314 } 315 316 } 317 }); 318 } catch (Throwable throwable) { 319 Log.e(TAG, "", throwable); 320 } 321 } 322 323 void scrollToPosition(final int position) throws Throwable { 324 runTestOnUiThread(new Runnable() { 325 @Override 326 public void run() { 327 mRecyclerView.getLayoutManager().scrollToPosition(position); 328 } 329 }); 330 } 331 332 void smoothScrollToPosition(final int position) 333 throws Throwable { 334 if (mDebug) { 335 Log.d(TAG, "SMOOTH scrolling to " + position); 336 } 337 runTestOnUiThread(new Runnable() { 338 @Override 339 public void run() { 340 mRecyclerView.smoothScrollToPosition(position); 341 } 342 }); 343 getInstrumentation().waitForIdleSync(); 344 Thread.sleep(200); //give scroller some time so start 345 while (mRecyclerView.getLayoutManager().isSmoothScrolling() || 346 mRecyclerView.getScrollState() != RecyclerView.SCROLL_STATE_IDLE) { 347 if (mDebug) { 348 Log.d(TAG, "SMOOTH scrolling step"); 349 } 350 Thread.sleep(200); 351 } 352 if (mDebug) { 353 Log.d(TAG, "SMOOTH scrolling done"); 354 } 355 getInstrumentation().waitForIdleSync(); 356 } 357 358 class TestViewHolder extends RecyclerView.ViewHolder { 359 360 Item mBoundItem; 361 362 public TestViewHolder(View itemView) { 363 super(itemView); 364 itemView.setFocusable(true); 365 } 366 367 @Override 368 public String toString() { 369 return super.toString() + " item:" + mBoundItem; 370 } 371 } 372 class DumbLayoutManager extends TestLayoutManager { 373 ReentrantLock mLayoutLock = new ReentrantLock(); 374 public void blockLayout() { 375 mLayoutLock.lock(); 376 } 377 378 public void unblockLayout() { 379 mLayoutLock.unlock(); 380 } 381 @Override 382 public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) { 383 mLayoutLock.lock(); 384 detachAndScrapAttachedViews(recycler); 385 layoutRange(recycler, 0, state.getItemCount()); 386 if (layoutLatch != null) { 387 layoutLatch.countDown(); 388 } 389 mLayoutLock.unlock(); 390 } 391 } 392 public class TestLayoutManager extends RecyclerView.LayoutManager { 393 int mScrollVerticallyAmount; 394 int mScrollHorizontallyAmount; 395 protected CountDownLatch layoutLatch; 396 397 public void expectLayouts(int count) { 398 layoutLatch = new CountDownLatch(count); 399 } 400 401 public void waitForLayout(long timeout, TimeUnit timeUnit, boolean waitForIdle) 402 throws Throwable { 403 layoutLatch.await(timeout * (mDebug ? 100 : 1), timeUnit); 404 assertEquals("all expected layouts should be executed at the expected time", 405 0, layoutLatch.getCount()); 406 if (waitForIdle) { 407 getInstrumentation().waitForIdleSync(); 408 } 409 } 410 411 public void waitForLayout(long timeout, TimeUnit timeUnit) 412 throws Throwable { 413 waitForLayout(timeout, timeUnit, true); 414 } 415 416 public void assertLayoutCount(int count, String msg, long timeout) throws Throwable { 417 layoutLatch.await(timeout, TimeUnit.SECONDS); 418 assertEquals(msg, count, layoutLatch.getCount()); 419 } 420 421 public void assertNoLayout(String msg, long timeout) throws Throwable { 422 layoutLatch.await(timeout, TimeUnit.SECONDS); 423 assertFalse(msg, layoutLatch.getCount() == 0); 424 } 425 426 public void waitForLayout(long timeout) throws Throwable { 427 waitForLayout(timeout * (mDebug ? 10000 : 1), TimeUnit.SECONDS, true); 428 } 429 430 public void waitForLayout(long timeout, boolean waitForIdle) throws Throwable { 431 waitForLayout(timeout * (mDebug ? 10000 : 1), TimeUnit.SECONDS, waitForIdle); 432 } 433 434 @Override 435 public RecyclerView.LayoutParams generateDefaultLayoutParams() { 436 return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 437 ViewGroup.LayoutParams.WRAP_CONTENT); 438 } 439 440 void assertVisibleItemPositions() { 441 int i = getChildCount(); 442 TestAdapter testAdapter = (TestAdapter) mRecyclerView.getAdapter(); 443 while (i-- > 0) { 444 View view = getChildAt(i); 445 RecyclerView.LayoutParams lp = (RecyclerView.LayoutParams) view.getLayoutParams(); 446 Item item = ((TestViewHolder) lp.mViewHolder).mBoundItem; 447 if (mDebug) { 448 Log.d(TAG, "testing item " + i); 449 } 450 if (!lp.isItemRemoved()) { 451 RecyclerView.ViewHolder vh = mRecyclerView.getChildViewHolder(view); 452 assertSame("item position in LP should match adapter value :" + vh, 453 testAdapter.mItems.get(vh.mPosition), item); 454 } 455 } 456 } 457 458 RecyclerView.LayoutParams getLp(View v) { 459 return (RecyclerView.LayoutParams) v.getLayoutParams(); 460 } 461 462 protected void layoutRange(RecyclerView.Recycler recycler, int start, int end) { 463 assertScrap(recycler); 464 if (mDebug) { 465 Log.d(TAG, "will layout items from " + start + " to " + end); 466 } 467 int diff = end > start ? 1 : -1; 468 int top = 0; 469 for (int i = start; i != end; i+=diff) { 470 if (mDebug) { 471 Log.d(TAG, "laying out item " + i); 472 } 473 View view = recycler.getViewForPosition(i); 474 assertNotNull("view should not be null for valid position. " 475 + "got null view at position " + i, view); 476 if (!mRecyclerView.mState.isPreLayout()) { 477 RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) view 478 .getLayoutParams(); 479 assertFalse("In post layout, getViewForPosition should never return a view " 480 + "that is removed", layoutParams != null 481 && layoutParams.isItemRemoved()); 482 483 } 484 assertEquals("getViewForPosition should return correct position", 485 i, getPosition(view)); 486 addView(view); 487 488 measureChildWithMargins(view, 0, 0); 489 if (getLayoutDirection() == ViewCompat.LAYOUT_DIRECTION_RTL) { 490 layoutDecorated(view, getWidth() - getDecoratedMeasuredWidth(view), top, 491 getWidth(), top + getDecoratedMeasuredHeight(view)); 492 } else { 493 layoutDecorated(view, 0, top, getDecoratedMeasuredWidth(view) 494 , top + getDecoratedMeasuredHeight(view)); 495 } 496 497 top += view.getMeasuredHeight(); 498 } 499 } 500 501 private void assertScrap(RecyclerView.Recycler recycler) { 502 if (mRecyclerView.getAdapter() != null && 503 !mRecyclerView.getAdapter().hasStableIds()) { 504 for (RecyclerView.ViewHolder viewHolder : recycler.getScrapList()) { 505 assertFalse("Invalid scrap should be no kept", viewHolder.isInvalid()); 506 } 507 } 508 } 509 510 @Override 511 public boolean canScrollHorizontally() { 512 return true; 513 } 514 515 @Override 516 public boolean canScrollVertically() { 517 return true; 518 } 519 520 @Override 521 public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, 522 RecyclerView.State state) { 523 mScrollHorizontallyAmount += dx; 524 return dx; 525 } 526 527 @Override 528 public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, 529 RecyclerView.State state) { 530 mScrollVerticallyAmount += dy; 531 return dy; 532 } 533 } 534 535 static class Item { 536 final static AtomicInteger idCounter = new AtomicInteger(0); 537 final public int mId = idCounter.incrementAndGet(); 538 539 int mAdapterIndex; 540 541 final String mText; 542 543 Item(int adapterIndex, String text) { 544 mAdapterIndex = adapterIndex; 545 mText = text; 546 } 547 548 @Override 549 public String toString() { 550 return "Item{" + 551 "mId=" + mId + 552 ", originalIndex=" + mAdapterIndex + 553 ", text='" + mText + '\'' + 554 '}'; 555 } 556 } 557 558 public class TestAdapter extends RecyclerView.Adapter<TestViewHolder> 559 implements AttachDetachCountingAdapter { 560 561 ViewAttachDetachCounter mAttachmentCounter = new ViewAttachDetachCounter(); 562 List<Item> mItems; 563 564 public TestAdapter(int count) { 565 mItems = new ArrayList<Item>(count); 566 for (int i = 0; i < count; i++) { 567 mItems.add(new Item(i, "Item " + i)); 568 } 569 } 570 571 @Override 572 public void onViewAttachedToWindow(TestViewHolder holder) { 573 super.onViewAttachedToWindow(holder); 574 mAttachmentCounter.onViewAttached(holder); 575 } 576 577 @Override 578 public void onViewDetachedFromWindow(TestViewHolder holder) { 579 super.onViewDetachedFromWindow(holder); 580 mAttachmentCounter.onViewDetached(holder); 581 } 582 583 @Override 584 public void onAttachedToRecyclerView(RecyclerView recyclerView) { 585 super.onAttachedToRecyclerView(recyclerView); 586 mAttachmentCounter.onAttached(recyclerView); 587 } 588 589 @Override 590 public void onDetachedFromRecyclerView(RecyclerView recyclerView) { 591 super.onDetachedFromRecyclerView(recyclerView); 592 mAttachmentCounter.onDetached(recyclerView); 593 } 594 595 @Override 596 public TestViewHolder onCreateViewHolder(ViewGroup parent, 597 int viewType) { 598 return new TestViewHolder(new TextView(parent.getContext())); 599 } 600 601 @Override 602 public void onBindViewHolder(TestViewHolder holder, int position) { 603 assertNotNull(holder.mOwnerRecyclerView); 604 assertEquals(position, holder.getAdapterPosition()); 605 final Item item = mItems.get(position); 606 ((TextView) (holder.itemView)).setText(item.mText + "(" + item.mAdapterIndex + ")"); 607 holder.mBoundItem = item; 608 } 609 610 public Item getItemAt(int position) { 611 return mItems.get(position); 612 } 613 614 @Override 615 public void onViewRecycled(TestViewHolder holder) { 616 super.onViewRecycled(holder); 617 final int adapterPosition = holder.getAdapterPosition(); 618 final boolean shouldHavePosition = !holder.isRemoved() && holder.isBound() && 619 !holder.isAdapterPositionUnknown() && !holder.isInvalid(); 620 String log = "Position check for " + holder.toString(); 621 assertEquals(log, shouldHavePosition, adapterPosition != RecyclerView.NO_POSITION); 622 if (shouldHavePosition) { 623 assertTrue(log, mItems.size() > adapterPosition); 624 assertSame(log, holder.mBoundItem, mItems.get(adapterPosition)); 625 } 626 } 627 628 public void deleteAndNotify(final int start, final int count) throws Throwable { 629 deleteAndNotify(new int[]{start, count}); 630 } 631 632 /** 633 * Deletes items in the given ranges. 634 * <p> 635 * Note that each operation affects the one after so you should offset them properly. 636 * <p> 637 * For example, if adapter has 5 items (A,B,C,D,E), and then you call this method with 638 * <code>[1, 2],[2, 1]</code>, it will first delete items B,C and the new adapter will be 639 * A D E. Then it will delete 2,1 which means it will delete E. 640 */ 641 public void deleteAndNotify(final int[]... startCountTuples) throws Throwable { 642 for (int[] tuple : startCountTuples) { 643 tuple[1] = -tuple[1]; 644 } 645 new AddRemoveRunnable(startCountTuples).runOnMainThread(); 646 } 647 648 @Override 649 public long getItemId(int position) { 650 return hasStableIds() ? mItems.get(position).mId : super.getItemId(position); 651 } 652 653 public void offsetOriginalIndices(int start, int offset) { 654 for (int i = start; i < mItems.size(); i++) { 655 mItems.get(i).mAdapterIndex += offset; 656 } 657 } 658 659 /** 660 * @param start inclusive 661 * @param end exclusive 662 * @param offset 663 */ 664 public void offsetOriginalIndicesBetween(int start, int end, int offset) { 665 for (int i = start; i < end && i < mItems.size(); i++) { 666 mItems.get(i).mAdapterIndex += offset; 667 } 668 } 669 670 public void addAndNotify(final int start, final int count) throws Throwable { 671 addAndNotify(new int[]{start, count}); 672 } 673 674 public void addAndNotify(final int[]... startCountTuples) throws Throwable { 675 new AddRemoveRunnable(startCountTuples).runOnMainThread(); 676 } 677 678 public void dispatchDataSetChanged() throws Throwable { 679 runTestOnUiThread(new Runnable() { 680 @Override 681 public void run() { 682 notifyDataSetChanged(); 683 } 684 }); 685 } 686 687 public void changeAndNotify(final int start, final int count) throws Throwable { 688 runTestOnUiThread(new Runnable() { 689 @Override 690 public void run() { 691 notifyItemRangeChanged(start, count); 692 } 693 }); 694 } 695 696 public void changePositionsAndNotify(final int... positions) throws Throwable { 697 runTestOnUiThread(new Runnable() { 698 @Override 699 public void run() { 700 for (int i = 0; i < positions.length; i += 1) { 701 TestAdapter.super.notifyItemRangeChanged(positions[i], 1); 702 } 703 } 704 }); 705 } 706 707 /** 708 * Similar to other methods but negative count means delete and position count means add. 709 * <p> 710 * For instance, calling this method with <code>[1,1], [2,-1]</code> it will first add an 711 * item to index 1, then remove an item from index 2 (updated index 2) 712 */ 713 public void addDeleteAndNotify(final int[]... startCountTuples) throws Throwable { 714 new AddRemoveRunnable(startCountTuples).runOnMainThread(); 715 } 716 717 @Override 718 public int getItemCount() { 719 return mItems.size(); 720 } 721 722 /** 723 * Uses notifyDataSetChanged 724 */ 725 public void moveItems(boolean notifyChange, int[]... fromToTuples) throws Throwable { 726 for (int i = 0; i < fromToTuples.length; i += 1) { 727 int[] tuple = fromToTuples[i]; 728 moveItem(tuple[0], tuple[1], false); 729 } 730 if (notifyChange) { 731 dispatchDataSetChanged(); 732 } 733 } 734 735 /** 736 * Uses notifyDataSetChanged 737 */ 738 public void moveItem(final int from, final int to, final boolean notifyChange) 739 throws Throwable { 740 runTestOnUiThread(new Runnable() { 741 @Override 742 public void run() { 743 moveInUIThread(from, to); 744 if (notifyChange) { 745 notifyDataSetChanged(); 746 } 747 } 748 }); 749 } 750 751 /** 752 * Uses notifyItemMoved 753 */ 754 public void moveAndNotify(final int from, final int to) throws Throwable { 755 runTestOnUiThread(new Runnable() { 756 @Override 757 public void run() { 758 moveInUIThread(from, to); 759 notifyItemMoved(from, to); 760 } 761 }); 762 } 763 764 protected void moveInUIThread(int from, int to) { 765 Item item = mItems.remove(from); 766 offsetOriginalIndices(from, -1); 767 mItems.add(to, item); 768 offsetOriginalIndices(to + 1, 1); 769 item.mAdapterIndex = to; 770 } 771 772 773 @Override 774 public ViewAttachDetachCounter getCounter() { 775 return mAttachmentCounter; 776 } 777 778 779 private class AddRemoveRunnable implements Runnable { 780 final int[][] mStartCountTuples; 781 782 public AddRemoveRunnable(int[][] startCountTuples) { 783 mStartCountTuples = startCountTuples; 784 } 785 786 public void runOnMainThread() throws Throwable { 787 if (Looper.myLooper() == Looper.getMainLooper()) { 788 run(); 789 } else { 790 runTestOnUiThread(this); 791 } 792 } 793 794 @Override 795 public void run() { 796 for (int[] tuple : mStartCountTuples) { 797 if (tuple[1] < 0) { 798 delete(tuple); 799 } else { 800 add(tuple); 801 } 802 } 803 } 804 805 private void add(int[] tuple) { 806 // offset others 807 offsetOriginalIndices(tuple[0], tuple[1]); 808 for (int i = 0; i < tuple[1]; i++) { 809 mItems.add(tuple[0], new Item(i, "new item " + i)); 810 } 811 notifyItemRangeInserted(tuple[0], tuple[1]); 812 } 813 814 private void delete(int[] tuple) { 815 final int count = -tuple[1]; 816 offsetOriginalIndices(tuple[0] + count, tuple[1]); 817 for (int i = 0; i < count; i++) { 818 mItems.remove(tuple[0]); 819 } 820 notifyItemRangeRemoved(tuple[0], count); 821 } 822 } 823 } 824 825 public boolean isMainThread() { 826 return Looper.myLooper() == Looper.getMainLooper(); 827 } 828 829 @Override 830 public void runTestOnUiThread(Runnable r) throws Throwable { 831 if (Looper.myLooper() == Looper.getMainLooper()) { 832 r.run(); 833 } else { 834 super.runTestOnUiThread(r); 835 } 836 } 837 838 static class TargetTuple { 839 840 final int mPosition; 841 842 final int mLayoutDirection; 843 844 TargetTuple(int position, int layoutDirection) { 845 this.mPosition = position; 846 this.mLayoutDirection = layoutDirection; 847 } 848 849 @Override 850 public String toString() { 851 return "TargetTuple{" + 852 "mPosition=" + mPosition + 853 ", mLayoutDirection=" + mLayoutDirection + 854 '}'; 855 } 856 } 857 858 public interface AttachDetachCountingAdapter { 859 860 ViewAttachDetachCounter getCounter(); 861 } 862 863 public class ViewAttachDetachCounter { 864 865 Set<RecyclerView.ViewHolder> mAttachedSet = new HashSet<RecyclerView.ViewHolder>(); 866 867 public void validateRemaining(RecyclerView recyclerView) { 868 final int childCount = recyclerView.getChildCount(); 869 for (int i = 0; i < childCount; i++) { 870 View view = recyclerView.getChildAt(i); 871 RecyclerView.ViewHolder vh = recyclerView.getChildViewHolder(view); 872 assertTrue("remaining view should be in attached set " + vh, 873 mAttachedSet.contains(vh)); 874 } 875 assertEquals("there should not be any views left in attached set", 876 childCount, mAttachedSet.size()); 877 } 878 879 public void onViewDetached(RecyclerView.ViewHolder viewHolder) { 880 try { 881 assertTrue("view holder should be in attached set", 882 mAttachedSet.remove(viewHolder)); 883 } catch (Throwable t) { 884 postExceptionToInstrumentation(t); 885 } 886 } 887 888 public void onViewAttached(RecyclerView.ViewHolder viewHolder) { 889 try { 890 assertTrue("view holder should not be in attached set", 891 mAttachedSet.add(viewHolder)); 892 } catch (Throwable t) { 893 postExceptionToInstrumentation(t); 894 } 895 } 896 897 public void onAttached(RecyclerView recyclerView) { 898 // when a new RV is attached, clear the set and add all view holders 899 mAttachedSet.clear(); 900 final int childCount = recyclerView.getChildCount(); 901 for (int i = 0; i < childCount; i ++) { 902 View view = recyclerView.getChildAt(i); 903 mAttachedSet.add(recyclerView.getChildViewHolder(view)); 904 } 905 } 906 907 public void onDetached(RecyclerView recyclerView) { 908 validateRemaining(recyclerView); 909 } 910 } 911} 912