Android Espresso-如果未选中,请单击复选框 [英] Android Espresso - Click checkbox if not checked
问题描述
我有onView(withId(R.id.check_box)).perform(click())
,但是我只想在尚未选中该复选框的情况下执行此操作.如何在浓缩咖啡中做到这一点?
I have onView(withId(R.id.check_box)).perform(click())
, but i only want to do this if the check box is not already checked. How can I do this in espresso?
推荐答案
我还想根据其先前状态来切换复选框/开关.一开始,我尝试过此操作以打开一个已关闭的复选框:
I also wanted to toggle a checkbox/switch depending on it's previous state. At first, I tried this to toggle ON a checkbox that was OFF:
onView(withId(R.id.checkbox)).check(matches(isNotChecked())).perform(scrollTo(), click());
...这可以关闭一个已打开的复选框:
...and this to toggle OFF a checkbox that was ON:
onView(withId(R.id.checkbox)).check(matches(isChecked())).perform(scrollTo(), click());
但是,这不起作用,因为Espresso将在执行操作之前先寻找特定的切换状态.有时,您事先不知道它是打开还是关闭.
However, this doesn't work, since Espresso will be looking for a specific toggle state before it performs the action. Sometimes, you don't know whether it's ON or OFF beforehand.
我的解决方案是使用自定义ViewAction来关闭/打开任何不依赖于先前状态的可检查对象(Switch,Checkbox等).因此,如果它已经打开,它将保持打开状态.如果关闭,它将切换为打开.这是ViewAction:
My solution is to use a custom ViewAction to turn OFF/ON any checkable object (Switch, Checkbox, etc.) that isn't dependent on previous state. So, if it's already ON, it'll stay ON. If it's OFF, it'll toggle ON. Here's the ViewAction:
public static ViewAction setChecked(final boolean checked) {
return new ViewAction() {
@Override
public BaseMatcher<View> getConstraints() {
return new BaseMatcher<View>() {
@Override
public boolean matches(Object item) {
return isA(Checkable.class).matches(item);
}
@Override
public void describeMismatch(Object item, Description mismatchDescription) {}
@Override
public void describeTo(Description description) {}
};
}
@Override
public String getDescription() {
return null;
}
@Override
public void perform(UiController uiController, View view) {
Checkable checkableView = (Checkable) view;
checkableView.setChecked(checked);
}
};
}
这是您的用法(在此示例中,当您想切换到开"时):
And here's how you use it (in this example, when you want to toggle to ON):
onView(withId(R.id.toggle)).perform(scrollTo(), setChecked(true));
这篇关于Android Espresso-如果未选中,请单击复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!