简体   繁体   English

使用 Espresso 单击 ListView 中的特定复选框

[英]Click on a specific checkbox in a ListView using Espresso

I have a ListView where each row has a checkbox:我有一个ListView ,其中每一行都有一个复选框:

在此处输入图片说明

Now I want to click on the checkbox in the 4th row.现在我想单击第 4 行中的复选框。 I have the data model for each row, so I can easily use onData() to select a row with the given data.我有每一行的数据模型,所以我可以轻松地使用onData()选择具有给定数据的行。 But how do I click on the checkbox in that row?但是如何单击该行中的复选框?

After a little research, I found DataInteraction.atPosition() and DataInteraction.onChildView() .经过一番研究,我找到了DataInteraction.atPosition()DataInteraction.onChildView() For example, I can do例如,我可以做

onData(instanceOf(BaseballCard.class))
            .atPosition(4)
            .onChildView(withId(R.id.checkmark))
            .perform(click());

If your row layout allows clicking on the row to set the CheckBox, you can use this to click the ListView row:如果您的行布局允许单击该行来设置 CheckBox,您可以使用它来单击 ListView 行:

onData(anything()).atPosition(4).perform(click());

Otherwise you can click directly on the CheckBox without knowing its ID:否则,您可以在不知道其 ID 的情况下直接单击 CheckBox:

onData(anything())
   .atPosition(4)
   .onChildView(withClassName(Matchers.containsString("CheckBox")))
   .perform(click());

You can then assert that the CheckBox is checked:然后,您可以断言 CheckBox 已被选中:

onData(anything())
   .atPosition(4)
   .onChildView(withClassName(Matchers.containsString("CheckBox")))
   .check(matches(isChecked()));

More info: https://github.com/shohrabuddin/Espresso更多信息: https : //github.com/shohrabuddin/Espresso


Note: To quickly add the imports for these methods, put the blinking cursor on the unresolved method, then do Android Studio ➔ HelpFind Action ➔ search for "show context action" or "show intention action" ➔ click on the result option ➔ A popup window will appear ➔ click on "Import static method ..." .注意:要快速添加这些方法的导入,请将闪烁的光标放在未解析的方法上,然后执行 Android Studio ➔帮助查找操作➔ 搜索"show context action""show intention action" ➔ 单击结果选项 ➔将出现一个弹出窗口 ➔ 单击"Import static method ..." You can also assign a keyboard shortcut to "Show Context Actions".您还可以为“显示上下文操作”分配键盘快捷键。 More info here . 更多信息在这里 Another way is to enable "Add unambiguous imports on the fly" in the Settings.另一种方法是在设置中启用"Add unambiguous imports on the fly" ”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM