Show entire bottom sheet with EditText above Keyboard

后端 未结 8 1360
北恋
北恋 2020-11-30 21:27

I\'m implementing a UI where a bottom sheet will appear above the keyboard with an EditText for the user to enter a value. The problem is the View is being partially overlap

8条回答
  •  爱一瞬间的悲伤
    2020-11-30 22:07

    For this, I found an AlertDialog worked best. While it doesn't sit flush against the bottom or side of the screen, it still looks good enough.

    First, create the AlertDialog with your view.

    val view = LayoutInflater.from(context).inflate(R.layout.alert, null)
    
    dialog = AlertDialog.Builder(context)
                 .setView(view)
                 .create()
    

    Next, set the gravity.

        dialog.window.attributes.gravity = Gravity.BOTTOM
    

    And finally, show it.

    dialog.show()
    

    You can also bind the keyboard to stay with the dialog, by using an onDismissListener.

    After showing the AlertDialog, I force up the keyboard.

    Call this method, passing in your EditText.

    fun showKeyboard(view: View?) {
            if (view == null) return;
    
            val imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
        }
    

    And for dismissing within the onDismissListener.

    private fun hideKeyboard() {
            val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0)
        }
    

提交回复
热议问题