我使用这个库中的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>
我有静态编程语言Android扩展启用,我尝试分配TextWatcherphoneNumber
如下:
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)
}
})
}
当我开始打字时,什么都没发生,浪费了几个小时…任何帮助都将不胜感激。
您正在onActivityCreated
中添加的textwatcher不包含您的根视图。您应该从View
中引用您的手机(TextInputEditText),在onCreateView
中膨胀,或者在onViewCreated
中膨胀,正如@Miha_x64所建议的那样。虽然您的代码是正确的,但问题在于视图引用。