android EditText 焦点行为

时间:2021-01-29 08:23:45

标签: android android-edittext focus

我认为这很容易实现,但显然不是。我有一个带有 2 个 editTexts 和 1 个 TextView 的片段。都有自定义的可绘制背景。这是我正在寻找的行为:

  1. 当片段打开时,没有任何焦点 - 工作正常
  2. 当您点击任一编辑时,它会获得焦点,选择所有文本,并且 softKeyboard 以数字模式打开 - 这也行
  3. 输入新号码后,当点击软键盘右下角的蓝色键(制表符或复选标记符号)时,软键盘关闭,没有任何焦点 - 没有闪烁的光标。 - 这就是我无法上班的原因
    请帮忙。 Kotlin 或 Java 可以

1 个答案:

答案 0 :(得分:0)

你需要实现这个逻辑(如果你愿意,你可以进一步升级,这只是一个例子)

布局:

...

        <View
            android:id="@+id/f_c_focus_view"
            android:focusable="true"
            android:focusableInTouchMode="true"
            android:layout_width="0dp"
            android:layout_height="0dp" />

        <EditText
            android:id="@+id/editText1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:imeOptions="actionDone"
            android:inputType="number" />

        <EditText
            android:id="@+id/editText2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:imeOptions="actionDone"
            android:inputType="number"/>
...

在布局中,您可以看到隐藏的“焦点”视图,这是拦截焦点所必需的,因为如果您将 EditText 作为视图的第一个组件,它将始终获得焦点。我的 EditText 组件有一个 imeOptions="actionDone",我将在代码中进一步处理它,您可以有不同的 imeOptions。

代码:

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

    ...

        focusView.requestFocus() // intercept focus on view created

        editText1.setOnEditorActionListener { v, actionId, _ ->
            when(actionId) {
                EditorInfo.IME_ACTION_DONE -> { // handle checkmark key press on the keyboard
                    v.clearFocus()
                    hideKeyBoard(v)
                }
            }

            false
        }

        editText2.setOnEditorActionListener { v, actionId, _ ->
            when(actionId) {
                EditorInfo.IME_ACTION_DONE -> {
                    v.clearFocus()
                    hideKeyBoard(v)
                }
            }

            false
        }

   ...
}

private fun hideKeyBoard(v: View) {
    val imm = context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(v.windowToken, 0)
}
相关问题