【问题标题】:How to Implement a TextWatcher in a DialogFragment如何在 DialogFragment 中实现 TextWatcher
【发布时间】:2020-01-24 11:09:56
【问题描述】:

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

但是,当 TextWatcher 从 onCreateDialog 连接到 EditText 时,我得到“java.lang.IllegalStateException: search_box must not be 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】:

    您的Edittext 似乎为空。

    确保您的Edittext 不为空

    val search_box = mainView.findViewById(R.id.youredittext) as EditText
    
    
    search_box.afterTextChanged {
       // do whatever
    }
    

    【讨论】:

      猜你喜欢
      • 2019-12-16
      • 1970-01-01
      • 1970-01-01
      • 2015-04-21
      • 1970-01-01
      • 1970-01-01
      • 2017-04-13
      • 2017-03-14
      • 2018-08-20
      相关资源
      最近更新 更多