【问题标题】:TextInputLayout clear focus when edittext is empty当edittext为空时TextInputLayout清除焦点
【发布时间】:2021-04-06 23:57:18
【问题描述】:

当editText 为空时,我想清除对TexInputLayout 的关注。如何在我的应用上设置该属性?

当应用程序运行时,editText 如下所示:

在我输入一些内容后,editText 看起来像:

当我删除 editText 中的所有内容时,它看起来像:

当 editText 为空时,我希望它看起来像第一张图片(当应用程序运行时)。我该怎么做?

com.google.android.material.textfield.TextInputLayout
                    android:id="@+id/user_phone"
                    
   style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:hint="Phone Number"
                    android:background="@color/white"
                    android:textColorHint="@color/black"
                    app:boxStrokeColor="@color/black"
                    app:boxStrokeWidthFocused="2dp"
                    app:endIconMode="clear_text"
                    app:endIconTint="@color/black"
                    app:startIconDrawable="@drawable/ic_phone"
                    app:startIconTint="@color/black">

                    <com.google.android.material.textfield.TextInputEditText
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:fontFamily="@font/muli_semibold"
                        android:inputType="phone"
                        android:textColor="@color/black" />

【问题讨论】:

    标签: android android-edittext focus android-textinputlayout


    【解决方案1】:

    首先,将android:focusable="true"android:focusableInTouchMode="true" 放到父视图组中。

    然后,您可以使用 TextWatcher 查看输入何时为空。在 kotlin 上会是这样的:

            editText.addTextChangedListener(object : TextWatcher {
                override fun afterTextChanged(s: Editable?) {
                    if (s.isNullOrEmpty()) {
                        // hide keyboard
                        val inputMethodManager = activity?.getSystemService(Activity.INPUT_METHOD_SERVICE) as? InputMethodManager
                        inputMethodManager?.hideSoftInputFromWindow(editText.windowToken, 0)
                        // remove focus
                        editText.clearFocus()
                    }
                }
    
                override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
    
                }
    
                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
    
                }
            })
    

    【讨论】:

    • 我使用 TextInputEditText 所以我不能使用 addTextChangedListener :)
    • 为什么不呢?这个:textInputLayout.editText?.addTextChangedListener(...) 不工作?您可以在TextInputEditText 上添加一个 id 或从TextInputLayout 获取editText,我想...自从我使用 TextInputEditText 已经有一段时间了
    猜你喜欢
    • 1970-01-01
    • 2019-01-02
    • 2013-07-03
    • 2013-06-08
    • 2013-03-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-25
    • 2018-02-10
    相关资源
    最近更新 更多