Android Robolectric Click RecyclerView Item

人走茶凉 提交于 2019-11-30 11:11:46

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

With Robolectric 3 you can use visible():

ActivityController<MyActivity> 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.

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

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