【问题标题】:TextWatcher not working in DialogFragmentTextWatcher 在 DialogFragment 中不起作用
【发布时间】:2019-12-16 23:36:14
【问题描述】:

我使用这个库中的TextInputLayout

implementation 'com.google.android.material:material:1.0.0'

我在布局中有以下部分:

            <com.google.android.material.textfield.TextInputLayout
                    android:id="@+id/phoneNumberLayout"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:errorEnabled="true">

                <com.google.android.material.textfield.TextInputEditText
                        android:id="@+id/phoneNumber"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:hint="@string/label_phone_number"/>
            </com.google.android.material.textfield.TextInputLayout>

我启用了 Kotlin Android 扩展,我尝试将 TextWatcher 分配给 phoneNumber,如下所示:

override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)

    phoneNumber.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {
            Log.e("DialogFragment", "phoneNumber::onTextChanged()")
        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            Log.e("DialogFragment", "phoneNumber current text: " + s)
        }
    })
}

当我开始打字时什么都没有发生,浪费了几个小时...任何帮助将不胜感激。

【问题讨论】:

  • 提供的 sn-p 看起来不错。检查您是否附加到正确的视图。布局中可能有多个具有相同 id 的视图?
  • onActivityCreated 似乎是错误的地方。试试onViewCreated,你的布局被膨胀并分配给一个片段。

标签: android kotlin android-edittext android-dialogfragment textwatcher


【解决方案1】:

您正在onActivityCreated 中添加 textwatcher,它不包含您的根视图。您应该按照@Miha_x64 的建议,从ViewonCreateViewonViewCreated 内部引用您的手机(TextInputEditText)。您的代码是正确的,但问题在于视图参考。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-19
    • 2015-04-19
    • 2015-03-01
    • 1970-01-01
    • 2019-09-24
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    相关资源
    最近更新 更多