捕获对话框编辑片段中的文本更改



我在Android Studio版本的花栗鼠与一个补丁。我在用Kotlin写作,一种我觉得很美的语言。我有一个对话框在一个片段,我想捕捉在编辑文本框的变化,因为他们发生。我已经尝试了在堆栈溢出中找到的直接代码,但我认为片段无法查看对话框。

使用的代码如下:

private fun dlgFind() {
try {
//val sTxt: EditText = findViewById(R.id.txtStock)
val sTxt = binding.txtMeds
val spannable: Spannable = SpannableString(sTxt.text.toString())
sTxt.setText(spannable.toString()) // clears highlighted text
val dialog = Dialog(requireContext(), R.style.RoundedCornersDialogFind)
dialog.window?.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND) // makes frag text readable
dialog.setContentView(R.layout.dlg_find)
// tried to max dialog window to full width of screen
//dialog.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
val btnFind = dialog.findViewById(R.id.btnGo) as ImageButton
val txtFind = dialog.findViewById(R.id.editFind) as EditText
txtFind.isFocusableInTouchMode = true
txtFind.isFocusable = true
//txtFind.inputType = InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
txtFind.requestFocus()
txtFind.postDelayed({
txtFind.requestFocus()
val imm = context?.getSystemService(INPUT_METHOD_SERVICE) as? InputMethodManager
imm?.showSoftInput(txtFind, InputMethodManager.SHOW_IMPLICIT)
}, 1)
btnFind.setOnClickListener { dialog.dismiss()
gsFindBoxTxt = txtFind.text.toString()
sTxt.requestFocus()
//sTxt.setText(spannable.toString()) // clears highlighted text
findWithDlg() // method finds strings
}
//dialog.setOnCancelListener { editHours() }
dialog.window?.setGravity(Gravity.BOTTOM)
dialog.show()
} catch (e: Exception) {
val methodName = object {}.javaClass.enclosingMethod?.name
Toast.makeText(context, methodName.toString(), Toast.LENGTH_LONG).show()
}
}

尝试从片段中的对话框中读取:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
try {
val sEditTxt = view.findViewById<EditText>(R.id.editFind)
sEditTxt?.doOnTextChanged { _, _, _, _ ->
Toast.makeText(context, "!", Toast.LENGTH_LONG).show() }
if (sEditTxt?.text != null) {
sEditTxt.doAfterTextChanged {
Toast.makeText(context, "!", Toast.LENGTH_LONG).show()
findWithDlg()
}
}
} catch (e: Exception) {
Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show()
}

注意我也尝试过样板文本观察代码,我不能在onCreate中返回视图,因为我在整个片段中使用绑定。onCreate的返回值是binding.root。甚至在onDestroyView中,最后一行是_binding = null。也许删除所有绑定并恢复使用视图?

我也在对话框方法(函数)中尝试了这些,但无济于事…

是的!我学会了怎么听课文的变化。我在对话框方法中设置如下:

dialog.setOnShowListener { txtFind.doOnTextChanged { _, _, _, _ ->
Toast.makeText(context, "Text Change", Toast.LENGTH_LONG).show()
} 
}

最新更新