问题
I have a ListView where each row has a checkbox:
Now I want to click on the checkbox in the 4th row. I have the data model for each row, so I can easily use onData() to select a row with the given data. But how do I click on the checkbox in that row?
回答1:
If your row layout allows clicking on the row to set the CheckBox, you can use this to click the ListView row:
onData(anything()).atPosition(4).perform(click());
Otherwise you can click directly on the CheckBox without knowing its ID:
onData(anything())
.atPosition(4)
.onChildView(withClassName(Matchers.containsString("CheckBox")))
.perform(click());
You can then assert that the CheckBox is checked:
onData(anything())
.atPosition(4)
.onChildView(withClassName(Matchers.containsString("CheckBox")))
.check(matches(isChecked()));
More info: https://github.com/shohrabuddin/Espresso
Note: To add quickly add the imports for these methods, put the blinking cursor on the unresolved method, then do Android Studio ➔ Help ➔ Find Action ➔ search for "show intention action" ➔ click on the result option ➔ A popup window will appear ➔ click on "Import static method ...". You can also assign a keyboard shortcut to "Show Intention Actions". More info here. Another way is to enable "Add unambiguous imports on the fly" in the Settings.
回答2:
After a little research, I found DataInteraction.atPosition() and DataInteraction.onChildView(). For example, I can do
onData(instanceOf(BaseballCard.class))
.atPosition(4)
.onChildView(withId(R.id.checkmark))
.perform(click());
来源:https://stackoverflow.com/questions/35395135/click-on-a-specific-checkbox-in-a-listview-using-espresso