简体   繁体   中英

Click on a specific checkbox in a ListView using Espresso

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?

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());

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 ➔ 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 ..." . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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