Android Studio中如何避免MaterialAlertDialogBuilder被键盘缩放?
解决MaterialAlertDialogBuilder对话框被键盘缩放遮挡的问题
给Dialog单独配置软输入模式
Activity清单里的android:windowSoftInputMode对Dialog兼容性不佳,直接给创建好的Dialog设置参数才更可靠。在调用dialog.show()之前添加以下代码:dialog.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)Java版本代码:
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);SOFT_INPUT_ADJUST_PAN会让屏幕整体上移避让键盘,不会缩放对话框,能保证对话框完整显示。检查自定义布局的根属性
自定义对话框的根布局不要用match_parent作为高度,改用wrap_content避免布局过度拉伸;同时给根布局加上android:fitsSystemWindows="true",帮助系统正确处理窗口边距。改用DialogFragment实现(更稳定)
如果上述方法未解决问题,换成DialogFragment来实现对话框,在onCreateDialog方法里配置软输入模式:override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dialog = MaterialAlertDialogBuilder(requireContext()) .setView(R.layout.your_custom_dialog_layout) .create() dialog.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN) return dialog }DialogFragment的生命周期管理更规范,对窗口参数的支持也更稳定。
排除干扰因素
检查Activity是否设置了android:windowFullscreen="true",全屏模式下软输入模式的行为会出现异常;另外确认自定义布局里的TextInputLayout没有设置不合理的高度属性,避免布局被挤压变形。
内容的提问来源于stack exchange,提问作者Bigo 20
相关产品推荐
相关产品推荐

