浓咖啡-如何点击随机的RecyclerView项目? [英] Espresso - How to click on a random RecyclerView item?

查看:69
本文介绍了浓咖啡-如何点击随机的RecyclerView项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有几篇文章显示了如何在带有Espresso的RecyclerView中单击某个已修复项目,例如:

There are a few posts that show how can you click a certain fixed item in the RecyclerView with Espresso, like:

如何在其中单击项目在Espresso中使用RecyclerView

使用Espresso单击RecyclerView项内的视图

示例:

//Change the 0 with any other number, will be the position of the item clicked.
onView(withId(R.id.a_main_recycler))
                .perform(RecyclerViewActions
                        .actionOnItemAtPosition(0, click()));


但是,如果您想单击RecyclerView中的随机项怎么办?


But, what if you want to click on a random item in the RecyclerView?

推荐答案

使用getActivity()方法.html#getActivity()"rel =" nofollow> ActivityTestRule .

Use the getActivity() method of ActivityTestRule.

您将能够使用findViewById()(在任何其他上下文中)和处理 RecyclerView实例.

You will be able to use findViewById() (as in any other context) and handle the RecyclerView instance.

示例:

@RunWith(AndroidJUnit4.class)
public class RandomBehaviorTest {

    //This rule provides functional testing of a single activity.
    @Rule
    public ActivityTestRule<MainActivity> mActivityRule =
            new ActivityTestRule<>(MainActivity.class);

    @Test
    public void clickRandomItem() {
        //Magic happening
        int x = getRandomRecyclerPosition(R.id.a_main_recycler);

        onView(withId(R.id.a_main_recycler))
                .perform(RecyclerViewActions
                        .actionOnItemAtPosition(x, click()));
    }

    private int getRandomRecyclerPosition(int recyclerId) {
        Random ran = new Random();
        //Get the actual drawn RecyclerView 
        RecyclerView recyclerView = (RecyclerView) mActivityRule
                .getActivity().findViewById(recyclerId);

        //If the RecyclerView exists, get the item count from the adapter
        int n = (recyclerView == null)
                ? 1
                : recyclerView.getAdapter().getItemCount();

        //Return a random number from 0 (inclusive) to adapter.itemCount() (exclusive) 
        return ran.nextInt(n);
    }

}

这篇关于浓咖啡-如何点击随机的RecyclerView项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆