BaseRecyclerViewInstrumentationTest.java revision f129f1b050d2542a91fe8175eac30183beb07b41
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.getPaddingLeft() + mRecyclerView.getWidth(), 176 mRecyclerView.getPaddingTop() + mRecyclerView.getHeight() 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.await(seconds, TimeUnit.SECONDS); 216 } 217 } 218 219 public boolean requestFocus(final View view) { 220 final boolean[] result = new boolean[1]; 221 getActivity().runOnUiThread(new Runnable() { 222 @Override 223 public void run() { 224 result[0] = view.requestFocus(); 225 } 226 }); 227 return result[0]; 228 } 229 230 public void setRecyclerView(final RecyclerView recyclerView) throws Throwable { 231 setRecyclerView(recyclerView, true); 232 } 233 public void setRecyclerView(final RecyclerView recyclerView, boolean assignDummyPool) 234 throws Throwable { 235 setRecyclerView(recyclerView, assignDummyPool, true); 236 } 237 public void setRecyclerView(final RecyclerView recyclerView, boolean assignDummyPool, 238 boolean addPositionCheckItemAnimator) 239 throws Throwable { 240 mRecyclerView = recyclerView; 241 if (assignDummyPool) { 242 RecyclerView.RecycledViewPool pool = new RecyclerView.RecycledViewPool() { 243 @Override 244 public RecyclerView.ViewHolder getRecycledView(int viewType) { 245 RecyclerView.ViewHolder viewHolder = super.getRecycledView(viewType); 246 if (viewHolder == null) { 247 return null; 248 } 249 viewHolder.addFlags(RecyclerView.ViewHolder.FLAG_BOUND); 250 viewHolder.mPosition = 200; 251 viewHolder.mOldPosition = 300; 252 viewHolder.mPreLayoutPosition = 500; 253 return viewHolder; 254 } 255 256 @Override 257 public void putRecycledView(RecyclerView.ViewHolder scrap) { 258 assertNull(scrap.mOwnerRecyclerView); 259 super.putRecycledView(scrap); 260 } 261 }; 262 mRecyclerView.setRecycledViewPool(pool); 263 } 264 if (addPositionCheckItemAnimator) { 265 mRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() { 266 @Override 267 public void getItemOffsets(Rect outRect, View view, RecyclerView parent, 268 RecyclerView.State state) { 269 RecyclerView.ViewHolder vh = parent.getChildViewHolder(view); 270 if (!vh.isRemoved()) { 271 assertNotSame("If getItemOffsets is called, child should have a valid" 272 + " adapter position unless it is removed : " + vh, 273 vh.getAdapterPosition(), RecyclerView.NO_POSITION); 274 } 275 } 276 }); 277 } 278 mAdapterHelper = recyclerView.mAdapterHelper; 279 runTestOnUiThread(new Runnable() { 280 @Override 281 public void run() { 282 getActivity().mContainer.addView(recyclerView); 283 } 284 }); 285 } 286 287 protected FrameLayout getRecyclerViewContainer() { 288 return getActivity().mContainer; 289 } 290 291 public void requestLayoutOnUIThread(final View view) { 292 try { 293 runTestOnUiThread(new Runnable() { 294 @Override 295 public void run() { 296 view.requestLayout(); 297 } 298 }); 299 } catch (Throwable throwable) { 300 Log.e(TAG, "", throwable); 301 } 302 } 303 304 public void scrollBy(final int dt) { 305 try { 306 runTestOnUiThread(new Runnable() { 307 @Override 308 public void run() { 309 if (mRecyclerView.getLayoutManager().canScrollHorizontally()) { 310 mRecyclerView.scrollBy(dt, 0); 311 } else { 312 mRecyclerView.scrollBy(0, dt); 313 } 314 315 } 316 }); 317 } catch (Throwable throwable) { 318 Log.e(TAG, "", throwable); 319 } 320 } 321 322 void scrollToPosition(final int position) throws Throwable { 323 runTestOnUiThread(new Runnable() { 324 @Override 325 public void run() { 326 mRecyclerView.getLayoutManager().scrollToPosition(position); 327 } 328 }); 329 } 330 331 void smoothScrollToPosition(final int position) 332 throws Throwable { 333 if (mDebug) { 334 Log.d(TAG, "SMOOTH scrolling to " + position); 335 } 336 runTestOnUiThread(new Runnable() { 337 @Override 338 public void run() { 339 mRecyclerView.smoothScrollToPosition(position); 340 } 341 }); 342 getInstrumentation().waitForIdleSync(); 343 Thread.sleep(200); //give scroller some time so start 344 while (mRecyclerView.getLayoutManager().isSmoothScrolling() || 345 mRecyclerView.getScrollState() != RecyclerView.SCROLL_STATE_IDLE) { 346 if (mDebug) { 347 Log.d(TAG, "SMOOTH scrolling step"); 348 } 349 Thread.sleep(200); 350 } 351 if (mDebug) { 352 Log.d(TAG, "SMOOTH scrolling done"); 353 } 354 getInstrumentation().waitForIdleSync(); 355 } 356 357 class TestViewHolder extends RecyclerView.ViewHolder { 358 359 Item mBoundItem; 360 361 public TestViewHolder(View itemView) { 362 super(itemView); 363 itemView.setFocusable(true); 364 } 365 366 @Override 367 public String toString() { 368 return super.toString() + " item:" + mBoundItem; 369 } 370 } 371 class DumbLayoutManager extends TestLayoutManager { 372 ReentrantLock mLayoutLock = new ReentrantLock(); 373 public void blockLayout() { 374 mLayoutLock.lock(); 375 } 376 377 public void unblockLayout() { 378 mLayoutLock.unlock(); 379 } 380 @Override 381 public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) { 382 mLayoutLock.lock(); 383 detachAndScrapAttachedViews(recycler); 384 layoutRange(recycler, 0, state.getItemCount()); 385 if (layoutLatch != null) { 386 layoutLatch.countDown(); 387 } 388 mLayoutLock.unlock(); 389 } 390 } 391 public class TestLayoutManager extends RecyclerView.LayoutManager { 392 int mScrollVerticallyAmount; 393 int mScrollHorizontallyAmount; 394 protected CountDownLatch layoutLatch; 395 396 public void expectLayouts(int count) { 397 layoutLatch = new CountDownLatch(count); 398 } 399 400 public void waitForLayout(long timeout, TimeUnit timeUnit) throws Throwable { 401 layoutLatch.await(timeout * (mDebug ? 100 : 1), timeUnit); 402 assertEquals("all expected layouts should be executed at the expected time", 403 0, layoutLatch.getCount()); 404 getInstrumentation().waitForIdleSync(); 405 } 406 407 public void assertLayoutCount(int count, String msg, long timeout) throws Throwable { 408 layoutLatch.await(timeout, TimeUnit.SECONDS); 409 assertEquals(msg, count, layoutLatch.getCount()); 410 } 411 412 public void assertNoLayout(String msg, long timeout) throws Throwable { 413 layoutLatch.await(timeout, TimeUnit.SECONDS); 414 assertFalse(msg, layoutLatch.getCount() == 0); 415 } 416 417 public void waitForLayout(long timeout) throws Throwable { 418 waitForLayout(timeout * (mDebug ? 10000 : 1), TimeUnit.SECONDS); 419 } 420 421 @Override 422 public RecyclerView.LayoutParams generateDefaultLayoutParams() { 423 return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 424 ViewGroup.LayoutParams.WRAP_CONTENT); 425 } 426 427 void assertVisibleItemPositions() { 428 int i = getChildCount(); 429 TestAdapter testAdapter = (TestAdapter) mRecyclerView.getAdapter(); 430 while (i-- > 0) { 431 View view = getChildAt(i); 432 RecyclerView.LayoutParams lp = (RecyclerView.LayoutParams) view.getLayoutParams(); 433 Item item = ((TestViewHolder) lp.mViewHolder).mBoundItem; 434 if (mDebug) { 435 Log.d(TAG, "testing item " + i); 436 } 437 if (!lp.isItemRemoved()) { 438 RecyclerView.ViewHolder vh = mRecyclerView.getChildViewHolder(view); 439 assertSame("item position in LP should match adapter value :" + vh, 440 testAdapter.mItems.get(vh.mPosition), item); 441 } 442 } 443 } 444 445 RecyclerView.LayoutParams getLp(View v) { 446 return (RecyclerView.LayoutParams) v.getLayoutParams(); 447 } 448 449 protected void layoutRange(RecyclerView.Recycler recycler, int start, int end) { 450 assertScrap(recycler); 451 if (mDebug) { 452 Log.d(TAG, "will layout items from " + start + " to " + end); 453 } 454 int diff = end > start ? 1 : -1; 455 int top = 0; 456 for (int i = start; i != end; i+=diff) { 457 if (mDebug) { 458 Log.d(TAG, "laying out item " + i); 459 } 460 View view = recycler.getViewForPosition(i); 461 assertNotNull("view should not be null for valid position. " 462 + "got null view at position " + i, view); 463 if (!mRecyclerView.mState.isPreLayout()) { 464 RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) view 465 .getLayoutParams(); 466 assertFalse("In post layout, getViewForPosition should never return a view " 467 + "that is removed", layoutParams != null 468 && layoutParams.isItemRemoved()); 469 470 } 471 assertEquals("getViewForPosition should return correct position", 472 i, getPosition(view)); 473 addView(view); 474 475 measureChildWithMargins(view, 0, 0); 476 if (getLayoutDirection() == ViewCompat.LAYOUT_DIRECTION_RTL) { 477 layoutDecorated(view, getWidth() - getDecoratedMeasuredWidth(view), top, 478 getWidth(), top + getDecoratedMeasuredHeight(view)); 479 } else { 480 layoutDecorated(view, 0, top, getDecoratedMeasuredWidth(view) 481 , top + getDecoratedMeasuredHeight(view)); 482 } 483 484 top += view.getMeasuredHeight(); 485 } 486 } 487 488 private void assertScrap(RecyclerView.Recycler recycler) { 489 if (mRecyclerView.getAdapter() != null && 490 !mRecyclerView.getAdapter().hasStableIds()) { 491 for (RecyclerView.ViewHolder viewHolder : recycler.getScrapList()) { 492 assertFalse("Invalid scrap should be no kept", viewHolder.isInvalid()); 493 } 494 } 495 } 496 497 @Override 498 public boolean canScrollHorizontally() { 499 return true; 500 } 501 502 @Override 503 public boolean canScrollVertically() { 504 return true; 505 } 506 507 @Override 508 public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, 509 RecyclerView.State state) { 510 mScrollHorizontallyAmount += dx; 511 return dx; 512 } 513 514 @Override 515 public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, 516 RecyclerView.State state) { 517 mScrollVerticallyAmount += dy; 518 return dy; 519 } 520 } 521 522 static class Item { 523 final static AtomicInteger idCounter = new AtomicInteger(0); 524 final public int mId = idCounter.incrementAndGet(); 525 526 int mAdapterIndex; 527 528 final String mText; 529 530 Item(int adapterIndex, String text) { 531 mAdapterIndex = adapterIndex; 532 mText = text; 533 } 534 535 @Override 536 public String toString() { 537 return "Item{" + 538 "mId=" + mId + 539 ", originalIndex=" + mAdapterIndex + 540 ", text='" + mText + '\'' + 541 '}'; 542 } 543 } 544 545 public class TestAdapter extends RecyclerView.Adapter<TestViewHolder> 546 implements AttachDetachCountingAdapter { 547 548 ViewAttachDetachCounter mAttachmentCounter = new ViewAttachDetachCounter(); 549 List<Item> mItems; 550 551 public TestAdapter(int count) { 552 mItems = new ArrayList<Item>(count); 553 for (int i = 0; i < count; i++) { 554 mItems.add(new Item(i, "Item " + i)); 555 } 556 } 557 558 @Override 559 public void onViewAttachedToWindow(TestViewHolder holder) { 560 super.onViewAttachedToWindow(holder); 561 mAttachmentCounter.onViewAttached(holder); 562 } 563 564 @Override 565 public void onViewDetachedFromWindow(TestViewHolder holder) { 566 super.onViewDetachedFromWindow(holder); 567 mAttachmentCounter.onViewDetached(holder); 568 } 569 570 @Override 571 public void onAttachedToRecyclerView(RecyclerView recyclerView) { 572 super.onAttachedToRecyclerView(recyclerView); 573 mAttachmentCounter.onAttached(recyclerView); 574 } 575 576 @Override 577 public void onDetachedFromRecyclerView(RecyclerView recyclerView) { 578 super.onDetachedFromRecyclerView(recyclerView); 579 mAttachmentCounter.onDetached(recyclerView); 580 } 581 582 @Override 583 public TestViewHolder onCreateViewHolder(ViewGroup parent, 584 int viewType) { 585 return new TestViewHolder(new TextView(parent.getContext())); 586 } 587 588 @Override 589 public void onBindViewHolder(TestViewHolder holder, int position) { 590 assertNotNull(holder.mOwnerRecyclerView); 591 assertEquals(position, holder.getAdapterPosition()); 592 final Item item = mItems.get(position); 593 ((TextView) (holder.itemView)).setText(item.mText + "(" + item.mAdapterIndex + ")"); 594 holder.mBoundItem = item; 595 } 596 597 public Item getItemAt(int position) { 598 return mItems.get(position); 599 } 600 601 @Override 602 public void onViewRecycled(TestViewHolder holder) { 603 super.onViewRecycled(holder); 604 final int adapterPosition = holder.getAdapterPosition(); 605 final boolean shouldHavePosition = !holder.isRemoved() && holder.isBound() && 606 !holder.isAdapterPositionUnknown() && !holder.isInvalid(); 607 String log = "Position check for " + holder.toString(); 608 assertEquals(log, shouldHavePosition, adapterPosition != RecyclerView.NO_POSITION); 609 if (shouldHavePosition) { 610 assertTrue(log, mItems.size() > adapterPosition); 611 assertSame(log, holder.mBoundItem, mItems.get(adapterPosition)); 612 } 613 } 614 615 public void deleteAndNotify(final int start, final int count) throws Throwable { 616 deleteAndNotify(new int[]{start, count}); 617 } 618 619 /** 620 * Deletes items in the given ranges. 621 * <p> 622 * Note that each operation affects the one after so you should offset them properly. 623 * <p> 624 * For example, if adapter has 5 items (A,B,C,D,E), and then you call this method with 625 * <code>[1, 2],[2, 1]</code>, it will first delete items B,C and the new adapter will be 626 * A D E. Then it will delete 2,1 which means it will delete E. 627 */ 628 public void deleteAndNotify(final int[]... startCountTuples) throws Throwable { 629 for (int[] tuple : startCountTuples) { 630 tuple[1] = -tuple[1]; 631 } 632 new AddRemoveRunnable(startCountTuples).runOnMainThread(); 633 } 634 635 @Override 636 public long getItemId(int position) { 637 return hasStableIds() ? mItems.get(position).mId : super.getItemId(position); 638 } 639 640 public void offsetOriginalIndices(int start, int offset) { 641 for (int i = start; i < mItems.size(); i++) { 642 mItems.get(i).mAdapterIndex += offset; 643 } 644 } 645 646 /** 647 * @param start inclusive 648 * @param end exclusive 649 * @param offset 650 */ 651 public void offsetOriginalIndicesBetween(int start, int end, int offset) { 652 for (int i = start; i < end && i < mItems.size(); i++) { 653 mItems.get(i).mAdapterIndex += offset; 654 } 655 } 656 657 public void addAndNotify(final int start, final int count) throws Throwable { 658 addAndNotify(new int[]{start, count}); 659 } 660 661 public void addAndNotify(final int[]... startCountTuples) throws Throwable { 662 new AddRemoveRunnable(startCountTuples).runOnMainThread(); 663 } 664 665 public void dispatchDataSetChanged() throws Throwable { 666 runTestOnUiThread(new Runnable() { 667 @Override 668 public void run() { 669 notifyDataSetChanged(); 670 } 671 }); 672 } 673 674 public void changeAndNotify(final int start, final int count) throws Throwable { 675 runTestOnUiThread(new Runnable() { 676 @Override 677 public void run() { 678 notifyItemRangeChanged(start, count); 679 } 680 }); 681 } 682 683 public void changePositionsAndNotify(final int... positions) throws Throwable { 684 runTestOnUiThread(new Runnable() { 685 @Override 686 public void run() { 687 for (int i = 0; i < positions.length; i += 1) { 688 TestAdapter.super.notifyItemRangeChanged(positions[i], 1); 689 } 690 } 691 }); 692 } 693 694 /** 695 * Similar to other methods but negative count means delete and position count means add. 696 * <p> 697 * For instance, calling this method with <code>[1,1], [2,-1]</code> it will first add an 698 * item to index 1, then remove an item from index 2 (updated index 2) 699 */ 700 public void addDeleteAndNotify(final int[]... startCountTuples) throws Throwable { 701 new AddRemoveRunnable(startCountTuples).runOnMainThread(); 702 } 703 704 @Override 705 public int getItemCount() { 706 return mItems.size(); 707 } 708 709 /** 710 * Uses notifyDataSetChanged 711 */ 712 public void moveItems(boolean notifyChange, int[]... fromToTuples) throws Throwable { 713 for (int i = 0; i < fromToTuples.length; i += 1) { 714 int[] tuple = fromToTuples[i]; 715 moveItem(tuple[0], tuple[1], false); 716 } 717 if (notifyChange) { 718 dispatchDataSetChanged(); 719 } 720 } 721 722 /** 723 * Uses notifyDataSetChanged 724 */ 725 public void moveItem(final int from, final int to, final boolean notifyChange) 726 throws Throwable { 727 runTestOnUiThread(new Runnable() { 728 @Override 729 public void run() { 730 moveInUIThread(from, to); 731 if (notifyChange) { 732 notifyDataSetChanged(); 733 } 734 } 735 }); 736 } 737 738 /** 739 * Uses notifyItemMoved 740 */ 741 public void moveAndNotify(final int from, final int to) throws Throwable { 742 runTestOnUiThread(new Runnable() { 743 @Override 744 public void run() { 745 moveInUIThread(from, to); 746 notifyItemMoved(from, to); 747 } 748 }); 749 } 750 751 protected void moveInUIThread(int from, int to) { 752 Item item = mItems.remove(from); 753 offsetOriginalIndices(from, -1); 754 mItems.add(to, item); 755 offsetOriginalIndices(to + 1, 1); 756 item.mAdapterIndex = to; 757 } 758 759 760 @Override 761 public ViewAttachDetachCounter getCounter() { 762 return mAttachmentCounter; 763 } 764 765 766 private class AddRemoveRunnable implements Runnable { 767 final int[][] mStartCountTuples; 768 769 public AddRemoveRunnable(int[][] startCountTuples) { 770 mStartCountTuples = startCountTuples; 771 } 772 773 public void runOnMainThread() throws Throwable { 774 if (Looper.myLooper() == Looper.getMainLooper()) { 775 run(); 776 } else { 777 runTestOnUiThread(this); 778 } 779 } 780 781 @Override 782 public void run() { 783 for (int[] tuple : mStartCountTuples) { 784 if (tuple[1] < 0) { 785 delete(tuple); 786 } else { 787 add(tuple); 788 } 789 } 790 } 791 792 private void add(int[] tuple) { 793 // offset others 794 offsetOriginalIndices(tuple[0], tuple[1]); 795 for (int i = 0; i < tuple[1]; i++) { 796 mItems.add(tuple[0], new Item(i, "new item " + i)); 797 } 798 notifyItemRangeInserted(tuple[0], tuple[1]); 799 } 800 801 private void delete(int[] tuple) { 802 final int count = -tuple[1]; 803 offsetOriginalIndices(tuple[0] + count, tuple[1]); 804 for (int i = 0; i < count; i++) { 805 mItems.remove(tuple[0]); 806 } 807 notifyItemRangeRemoved(tuple[0], count); 808 } 809 } 810 } 811 812 public boolean isMainThread() { 813 return Looper.myLooper() == Looper.getMainLooper(); 814 } 815 816 @Override 817 public void runTestOnUiThread(Runnable r) throws Throwable { 818 if (Looper.myLooper() == Looper.getMainLooper()) { 819 r.run(); 820 } else { 821 super.runTestOnUiThread(r); 822 } 823 } 824 825 static class TargetTuple { 826 827 final int mPosition; 828 829 final int mLayoutDirection; 830 831 TargetTuple(int position, int layoutDirection) { 832 this.mPosition = position; 833 this.mLayoutDirection = layoutDirection; 834 } 835 836 @Override 837 public String toString() { 838 return "TargetTuple{" + 839 "mPosition=" + mPosition + 840 ", mLayoutDirection=" + mLayoutDirection + 841 '}'; 842 } 843 } 844 845 public interface AttachDetachCountingAdapter { 846 847 ViewAttachDetachCounter getCounter(); 848 } 849 850 public class ViewAttachDetachCounter { 851 852 Set<RecyclerView.ViewHolder> mAttachedSet = new HashSet<RecyclerView.ViewHolder>(); 853 854 public void validateRemaining(RecyclerView recyclerView) { 855 final int childCount = recyclerView.getChildCount(); 856 for (int i = 0; i < childCount; i++) { 857 View view = recyclerView.getChildAt(i); 858 RecyclerView.ViewHolder vh = recyclerView.getChildViewHolder(view); 859 assertTrue("remaining view should be in attached set " + vh, 860 mAttachedSet.contains(vh)); 861 } 862 assertEquals("there should not be any views left in attached set", 863 childCount, mAttachedSet.size()); 864 } 865 866 public void onViewDetached(RecyclerView.ViewHolder viewHolder) { 867 try { 868 assertTrue("view holder should be in attached set", 869 mAttachedSet.remove(viewHolder)); 870 } catch (Throwable t) { 871 postExceptionToInstrumentation(t); 872 } 873 } 874 875 public void onViewAttached(RecyclerView.ViewHolder viewHolder) { 876 try { 877 assertTrue("view holder should not be in attached set", 878 mAttachedSet.add(viewHolder)); 879 } catch (Throwable t) { 880 postExceptionToInstrumentation(t); 881 } 882 } 883 884 public void onAttached(RecyclerView recyclerView) { 885 // when a new RV is attached, clear the set and add all view holders 886 mAttachedSet.clear(); 887 final int childCount = recyclerView.getChildCount(); 888 for (int i = 0; i < childCount; i ++) { 889 View view = recyclerView.getChildAt(i); 890 mAttachedSet.add(recyclerView.getChildViewHolder(view)); 891 } 892 } 893 894 public void onDetached(RecyclerView recyclerView) { 895 validateRemaining(recyclerView); 896 } 897 } 898} 899