【发布时间】: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