android - Espresso 为 edittext 设置光标

标签 android android-espresso

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

最佳答案

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

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).

关于android - Espresso 为 edittext 设置光标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50458393/

相关文章:

python - 如何在kivy python中通过滑动来更改屏幕

java - 处理程序删除回调并再次放入 ACTION_UP

java - Android BuildConfig 类值为空

android - 在 travis support-v4 21.0 上找不到 android.support.v4.widget.DrawerLayoutImpl 的类文件

android - Android 应用程序中的连接管理器

android - 在 FrameLayout 中添加 Google Maps Android API v2 MapFragment 和 View

android - CountingIdlingResource 的 IllegalAccessError

android - onChildView 和 hasSiblings 与 Espresso

shell - 停止 Android Studio shell 进程不会停止测试

android - Android Espresso 包 `android.support.test.espresso.intent` 的依赖项是什么?