Espresso 为 edittext 设置光标

Espresso set cursor for edittext

我正在尝试使用 Espresso 测试已经包含一些文本的 EditText。问题是当我使用 typeText() 时,光标位于文本中的任意位置。我尝试在使用 typeTextIntoFocusedView 之前执行 click(),但光标有时位于 EditText 的开头。我想知道是否可以在输入文本之前将光标设置在 EditText 的末尾?

我发现这样做的唯一方法是获取对 EditText 本身的引用并使用 EditText#setSelection()。例如,要将光标移动到当前文本的末尾:

    val activity = activityRule.activity
    val tv = activity.findViewById<EditText>(R.id.edittext)
    activity.runOnUiThread { tv.setSelection(tv.text.length) } 

我成功地为 "Home" 和 "End" 插入了 KeyCode。通过将光标移动到 EditText 的开头或结尾,这些操作就像在桌面键盘上一样。例如:

onView(withId(R.id.myView))
    .perform(pressKey(KeyEvent.KEYCODE_MOVE_HOME))

要移动到最后,您可以使用KeyEvent.KEYCODE_MOVE_END,您可以使用KeyEvent.KEYCODE_DPAD_LEFTKeyEvent.KEYCODE_DPAD_RIGHT向左或向右移动。

我想 post 我的答案,因为我刚遇到这个问题,none 其他答案解决了我的问题。

我使用 GeneralClickAction 单击编辑文本的右侧,将光标置于 EditText 末尾我想要的位置。之后,我使用 TypeTextAction 并通过将 false 传递给构造函数来禁用 tapToFocus 行为:

onView(withId(R.id.edit_text))
.perform(
  new GeneralClickAction(Tap.SINGLE, GeneralLocation.CENTER_RIGHT, Press.FINGER, 0, 0, null),
  new TypeTextAction(text, false)
);

更好的方法是按预期的方式使用 Espresso:在视图匹配器上执行操作。

Kotlin 中的示例:

class SetEditTextSelectionAction(private val selection: Int) : ViewAction {

    override fun getConstraints(): Matcher<View> {
        return allOf(isDisplayed(), isAssignableFrom(EditText::class.java))
    }

    override fun getDescription(): String {
        return "set selection to $selection"
    }

    override fun perform(uiController: UiController, view: View) {
        (view as EditText).setSelection(selection)
    }
}

用法示例:

onView(withId(R.id.my_text_view).perform(SetEditTextSelectionAction(selection))

与手动执行 findViewById() 相比的一个额外优势是,如果您没有视图的 ID,则可以将其与 withSubString("my text") 等匹配器结合使用。

顺便说一句:要将其更改为文本末尾的设置选择,您只需删除 selection: Int 构造函数参数并将 setSelection(selection) 更改为 setSelection(view.text.lastIndex).