Android Robolectric Click RecyclerView Item

匿名 (未验证) 提交于 2019-12-03 02:06:01

问题:

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).



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!