Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
98 views
in Technique[技术] by (71.8m points)

android EditText focus behavior


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to implement this logic (you can upgrade it further if you want, it's just an example)

Layout:

...

        <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"/>
...

In layout you can see hidden 'focus' view, it necessary for interception focus, because if you have an EditText as first component of the view it always will receive the focus. My EditText components have an imeOptions="actionDone" which I will handle in code further, you can have different imeOptions.

Code:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...