Reputation: 83577
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?
Upvotes: 4
Views: 1442
Reputation: 7661
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 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 context action"
or "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 Context Actions". More info here. Another way is to enable "Add unambiguous imports on the fly"
in the Settings.
Upvotes: 1
Reputation: 83577
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());
Upvotes: 1