键入时不调用TextInputEditText addTextChangedListener

时间:2018-11-02 19:35:14

标签: android kotlin material-design

我的表单很简单,只有一个TextInputEditText(材料设计组件),无法收听文本更改。将TextWatcheraddTextChangedListener相加似乎无效。当我运行我的应用程序并使用虚拟键盘键入输入时,没有调用任何回调(未击中调试断点),并且我的TextView没有更新:

活动:

class MainActivity : AppCompatActivity() {


    private lateinit var webBankingIdLayout: TextInputLayout
    private lateinit var webBankingIdInput: TextInputEditText
    private lateinit var textView: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        webBankingIdLayout = findViewById<TextInputLayout>(R.id.web_banking_id_input_layout)
        webBankingIdInput = TextInputEditText(webBankingIdLayout.context)
        textView = findViewById<TextView>(R.id.temp_text)

        webBankingIdInput.addTextChangedListener(object: TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                s!!
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                s!!
                textView.text = s!!
            }
            override fun afterTextChanged(s: Editable?) {
                s!!
            }
        })
    }
}

活动布局:

<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/web_banking_id_input_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox">

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/web_banking_id_text_input"
        android:maxLines="1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:baselineAligned="false"
        android:inputType="text"
        android:hint="@string/web_banking_id_hint" />

</com.google.android.material.textfield.TextInputLayout>

<TextView
    android:id="@+id/temp_text"
    android:layout_width="250dp"
    android:layout_height="113dp"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/password_input_layout" />

但是,如果我以编程方式设置输入字段的文本,则会调用回调并更新TextView

webBankingIdInput.text = "Yippee!"

为什么我的代码不起作用,如何收听字符输入到文本输入中?

我的目标是隐藏按钮,直到在该字段中输入的字符数最少为止。

2 个答案:

答案 0 :(得分:1)

您需要替换:

webBankingIdInput = TextInputEditText(webBankingIdLayout.context)

收件人:

webBankingIdInput = findViewById<TextInputEditText>(R.id.web_banking_id_text_input)

答案 1 :(得分:0)

我遇到了类似的问题,这是由于未在XML中设置android:inputType参数引起的。