簡體   English   中英

requestFocus() 在 EditText 上,解雇 BotSheetDialog w/o 隱藏鍵盤和鍵盤奇怪地出現

[英]requestFocus() on EditText, dismiss BotSheetDialog w/o hide keyboard and keyboard strangely show up

我在 BotSheetDialog 中有一個 EditText,它在 onViewCreated() 上有 requestFocus()。 然后我可以通過兩種方式關閉對話框:單擊“保存”按鈕或單擊對話框外部。 如果我手動按下隱藏鍵盤按鈕,它將按預期工作。 但如果我不這樣做,鍵盤將無處顯示。

// BottomDialog.kt
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        loadArgs()
        setClickListeners()
        binding.etTitle.requestFocus()
    }

我曾嘗試在 Destroy View 之前對其進行 clearFocus(),但它不起作用。

// BottomDialog.kt
override fun onDestroyView() {
        binding.etTitle.clearFocus()
        super.onDestroyView()
    }

預先感謝您:以下是數字:

https://i.stack.imgur.com/TGBQG.png
https://i.stack.imgur.com/eUn5s.png

更新

// My fun to hide keyboard
fun Activity.hideSoftKeyboard(view: View? = null) : Boolean {
    val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as
            InputMethodManager
    if (inputMethodManager.isAcceptingText) {
        if (view == null) {
            inputMethodManager.hideSoftInputFromWindow(this.currentFocus?.windowToken, 0)
        } else {
            inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
        }
        return true
    }
    return false
}
  • 我試圖在對話框的循環事件中調用它:
// BottomDialog.kt
override fun onPause() {
        val res = requireActivity().hideSoftKeyboard(binding.etTitle)
        log("onPause, $res")
        super.onPause()
    }

    override fun onStop() {
        val res = requireActivity().hideSoftKeyboard(binding.etTitle)
        log("onStop, $res")
        super.onStop()
    }

    override fun onDestroyView() {
        val res = requireActivity().hideSoftKeyboard(binding.etTitle)
        log("onDestroyView, $res")
        super.onDestroyView()
    }

    override fun onDestroy() {
        val res = requireActivity().hideSoftKeyboard(binding.etTitle)
        log("onDestroy, $res")
        super.onDestroy()
    }
/*
    Logcat:
    onPause, false
    onStop, false
    onDestroyView, false
    onDestroy, false
 */

我解決了它:

// AndroidManifest.xml
<activity
    ...
// Change this
    android:windowSoftInputMode="stateVisible|adjustPan"

// Into this
    android:windowSoftInputMode="adjustPan"
    ...
</activity>

使用下面的 fun 來隱藏鍵盤:

fun dismissKeyboard() {
    val inputMethodManager = getSystemService( Context.INPUT_METHOD_SERVICE ) as InputMethodManager
    if( inputMethodManager.isAcceptingText )
        inputMethodManager.hideSoftInputFromWindow( this.currentFocus.windowToken, 0)
}

暫無
暫無

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

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