可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
Is there any way to simulate a click on a RecyclerView
item with Robolectric?
So far, I have tried getting the View
at the first visible position of the RecyclerView
, but that is always null
. It's getChildCount()
keeps returning 0
, and findViewHolderForPosition
is always null
. The adapter returns a non-0 number from getItemCount()
(there are definitely items in the adapter).
I'm using Robolectric 2.4 SNAPSHOT.
回答1:
Seems like the issue was that RecyclerView
needs to be measured and layed out manually in Robolectric. Calling this solves the problem:
recyclerView.measure(0, 0); recyclerView.layout(0, 0, 100, 10000);
回答2:
With Robolectric 3 you can use visible():
ActivityController activityController = Robolectric.buildActivity(MyActivityclass); activityController.create().start().visible(); ShadowActivity myActivityShadow = shadowOf(activityController.get()); RecyclerView currentRecyclerView = ((RecyclerView) myActivityShadow.findViewById(R.id.myrecyclerid)); currentRecyclerView.getChildAt(0).performClick();
This eliminates the need to trigger the measurement of the view by hand.
回答3:
Expanding on Marco Hertwig's answer:
You need to add the recyclerView
to an activity so that its layout methods are called as expected. You could call them manually, (like in Elizer's answer) but you would have to manage the state yourself. Also, this would not be simulating an actual use-case.
Code:
@Before public void setup() { ActivityController activityController = Robolectric.buildActivity(Activity.class); // setup a default Activity Activity activity = activityController.get(); /* Setup the recyclerView (create it, add the adapter, add a LayoutManager, etc.) ... */ // set the recyclerView object as the only view in the activity activity.setContentView(recyclerView); // start the activity activityController.create().start().visible(); }
Now you don't need to worry about calling layout
and measure
everytime your recyclerView
is updated (by adding/removing items from the adapter
, for example).