gpt4 book ai didi

android - Espresso - 如何点击随机的 RecyclerView 项目?

转载 作者:行者123 更新时间:2023-11-29 17:24:04 25 4
gpt4 key购买 nike

有几篇文章展示了如何使用 Espresso 单击 RecyclerView 中的某个固定 项目,例如:

How to click on an item inside a RecyclerView in Espresso

Using Espresso to click view inside RecyclerView item


示例:

//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 中点击一个随机项怎么办?

最佳答案

使用ActivityTestRulegetActivity()方法.

您将能够使用 findViewById()(与在任何其他上下文中一样)并处理 RecyclerView 实例。


示例:

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

}

关于android - Espresso - 如何点击随机的 RecyclerView 项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35306033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com