如何在DialogFragment中实现TextWatcher

问题描述 投票:0回答:1

在我的应用程序中,我在Dialog片段中创建了一个可搜索的列表。顶部是我的editText,上面已应用了TextWatcher。

但是,当TextWatcher从onCreateDialog内连接到EditText时,出现“ java.lang.IllegalStateException:search_box不能为null”。当将其放置在onViewCreated内时,甚至不会调用onViewCreated。

有人可以解释我所缺少的吗?提前非常感谢

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    val layoutInflater = activity.layoutInflater
    val mainView = layoutInflater.inflate(R.layout.search_p, null)
    val builder = AlertDialog.Builder(activity)
    builder.setView(mainView)

    val layout = mainView.findViewById(R.id.results_layout) as LinearLayout
    var line = 0

    for(i in nameList){
        createButton(line,layout)
        line++
    }

    //Below line: java.lang.IllegalStateException: search_box must not be null
    search_box.afterTextChanged {
        val search = search_box.text.toString().toLowerCase()
        line = 0
        layout.removeAllViews()
        for(i in nameList){
            if(contains(search,nameList[line].toLowerCase())){
                createButton(line,layout)
            }
            line++
        }
    }

    return builder.create()
}

private fun EditText.afterTextChanged(afterTextChanged: (String)-> Unit) {
    this.addTextChangedListener(object: TextWatcher {
        override fun beforeTextChanged(p0:CharSequence?,p1:Int,p2:Int,p3:Int) { }
        override fun onTextChanged(p0:CharSequence?,p1:Int,p2:Int,p3:Int) {  }
        override fun afterTextChanged(editable: Editable?){
            afterTextChanged.invoke(editable.toString())
        }
    }) }
kotlin android-dialogfragment textwatcher
1个回答
0
投票

似乎您的edittext为null,这就是为什么它会抛出确保您的Edittext不为空

val search_box = mainView.findViewById(R.id.youredittext) as EditText


search_box.afterTextChanged {
   // do whatever
}
© www.soinside.com 2019 - 2024. All rights reserved.