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類型。