簡體   English   中英

在 DialogFragment 中關閉軟鍵盤時如何顯示和隱藏

[英]How to show and hide when dismissed the soft keyboard in a DialogFragment

我有一個帶有單個輸入文本的自定義DialogFragment ,當顯示對話框時,我將顯示鍵盤,當按下完成按鈕或按下肯定按鈕或關閉對話框以隱藏該鍵盤時。

我試圖將鍵盤顯示如下:

private fun showKeyboard() {
    val inputMethodManager = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    inputMethodManager.showSoftInput(view?.findViewById(R.id.quantity), 0)
}
override fun onResume() {
    super.onResume()
    showKeyboard()
}

並以這種方式隱藏它:

private fun closeKeyboard() {
    val inputMethodManager = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    inputMethodManager.hideSoftInputFromWindow(view?.windowToken, 0)
}
override fun onDestroy() {
    super.onDestroy()
    closeKeyboard()
}

但是鍵盤沒有顯示,如果我專注於輸入並嘗試關閉對話框,鍵盤仍然存在。

我通過將isCancelable設置為false解決了這個問題,因為我無法在覆蓋點擊時隱藏鍵盤。 我設法在關閉對話框的每個操作中使用 function hideKeyboard() ,因此當它等於IME_ACTION_DONE時,正負按鈕和編輯器操作。

在顯示對話框時顯示鍵盤時,我添加了以下代碼:

 dialog.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)

所以這是我的 DialogFragment 的代碼:

private fun hideKeyboard() {
    val im: InputMethodManager = requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    im.hideSoftInputFromWindow(quantity.windowToken, 0)
}

private lateinit var quantity: EditText

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    return activity?.let {
        val builder = AlertDialog.Builder(requireContext())
        val view = layoutInflater.inflate(R.layout.dialog_quantity_input, null)

        isCancelable = false
        quantity = view.findViewById(R.id.quantity)

        builder.setView(view)

        viewModel.selectedProduct.value.let {
            quantity.setText(it?.quantity.toString())
        }

        builder.setTitle("Modifica quantità")

        builder.setPositiveButton("Conferma") { _, _ ->
            ...
            hideKeyboard()
        }

        builder.setNegativeButton("Annulla") { _, _ ->
            hideKeyboard()
        }

        quantity.setOnEditorActionListener { v, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                ...
                hideKeyboard()
                dismiss()
            }
            false
        }

        quantity.requestFocus()

        val dialog = builder.create()
        dialog.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)

        return dialog
    } ?: throw IllegalStateException("Activity cannot be null")
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM