我在BottomSheet中有EditText。当显示BottomSheet时,我点击EditText,然后显示软键盘。但是,当BottomSheet中值Edittext的长度为6时,如何隐藏软键盘?
我有这样的逻辑:
private fun showBottomSheet() {
val binding: BottomSheetSetupEasyPinBinding =
DataBindingUtil.inflate(LayoutInflater.from(activity), R.layout.bottom_sheet_setup_easy_pin, null, false)
binding.fragment = this
binding.vm = vm
binding.lifecycleOwner = this
//For hide softKeyboard
binding.etEasyPinConfirmation.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable) {
}
override fun beforeTextChanged(s: CharSequence, start: Int,
count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence, start: Int,
before: Int, count: Int) {
if (s.length == 6) {
hideSoftKeyboard()
Toast.makeText(activity, "Length is 6", Toast.LENGTH_SHORT).show()
}
}
})
bottomSheet.setContentView(binding.root)
bottomSheet.setCancelable(false)
bottomSheet.show()
}
这是隐藏软键盘的功能:
fun hideSoftKeyboard() {
inputMethodManager.hideSoftInputFromWindow(view!!.windowToken, 0)
}
这是全局变量,并在onViewCreated
中声明该变量:
// global variable
private lateinit var inputMethodManager : InputMethodManager
..
// in onViewCreated
inputMethodManager = requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
但是当值EditText的长度为6时,将显示Toast,并且已经调试了该函数,但键盘没有隐藏。有谁知道为什么我的代码无法在BottomSheet中隐藏软键盘?因为如果EditText不在BottomSheet中,则此功能可以成功隐藏软键盘。
使用此更新方法的kotlin版本
fun Activity.hideKeyboard() {
hideKeyboard(currentFocus ?: View(this))
}
fun Context.hideKeyboard(view: View) {
val inputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as
InputMethodManager
inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
}
将您的代码放入ontextafterchange()方法中