Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

android EditText focus behavior


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

1 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...