replaceText
/**
* Returns an action that updates the text attribute of a view. <br>
* <br>
* View preconditions:
*
* <ul>
* <li>must be displayed on screen
* <li>must be assignable from EditText
* <ul>
*/
public static ViewAction replaceText(@Nonnull String stringToBeSet) {
return actionWithAssertions(new ReplaceTextAction(stringToBeSet));
}
该方法返回一个ViewAction类型对象,通过指定字符串替换控件内容,view有以下几个限制:
- 必须展示在屏幕上,即该视图的visibility不能是gone
- 必须是EditText类型。
如果该控件的visibility="gone"或者该控件不是EditText类型,则会报错。
typeText
/**
* Returns an action that selects the view (by clicking on it) and types the provided string into
* the view. Appending a \n to the end of the string translates to a ENTER key event. Note: this
* method performs a tap on the view before typing to force the view into focus, if the view
* already contains text this tap may place the cursor at an arbitrary position within the text.
* <br>
* <br>
* View preconditions:
*
* <ul>
* <li>must be displayed on screen
* <li>must support input methods
* <ul>
*/
public static ViewAction typeText(String stringToBeTyped) {
return actionWithAssertions(new TypeTextAction(stringToBeTyped));
}
该方法返回一个ViewAction类型对象,不过该方法是模拟键盘输入方式输入字符串,所以该方法不能输入汉字,且有以下限制:
- 必须展示在屏幕上
- 必须是可输入类型控件
使用方法
onView(withId(R.id.edit)).perform(ViewActions.typeText("aaa"));//方法一
onView(withId(R.id.edit)).perform(ViewActions.replaceText("测试"));//方法二
方法一
ViewActions.typeText("aaa")最终返回的是一个TypeTextAction类型,perform最终调用的是viewAction.perform(uiController, targetView)方法,该viewAction就是TypeTextAction类型,所以最终会调用TypeTextAction的perform
@Override
public void perform(UiController uiController, View view) {
......
if (tapToFocus) {
// Perform a click.
new GeneralClickAction(Tap.SINGLE, GeneralLocation.CENTER, Press.FINGER)
.perform(uiController, view);
uiController.loopMainThreadUntilIdle();
}
......
}
最终会模拟键盘输入的方式输入字符串,而键盘上是不存在中文字符的,所以输入中文字符会报错。
方法二
ViewActions.replaceText("测试")最终返回的是一个ReplaceTextAction类型,perform最终调用的是viewAction.perform(uiController, targetView)方法,该viewAction就是ReplaceTextAction类型,所以最终会调用ReplaceTextAction的perform
@Override
public void perform(UiController uiController, View view) {
((EditText) view).setText(stringToBeSet);
}
由上可以看出,目标控件必须是EditText类型。
网友评论