Android 11中DialogFragment自定义对话框软键盘开关后布局偏移求助
解决方案
针对Android 11上DialogFragment在软键盘开关后视图右偏的问题,可通过以下几种方式解决:
方法一:强制控制Dialog窗口参数
重写DialogFragment的onCreateDialog方法,明确设置窗口的宽度、对齐方式及软输入模式,避免系统自动调整导致偏移:
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dialog = super.onCreateDialog(savedInstanceState) dialog.window?.run { // 设置窗口为全屏宽度,高度自适应 setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) // 软键盘调整时仅重布局,不平移窗口 setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE or WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) if (Build.VERSION.SDK_INT == Build.VERSION_CODES.R) { // Android 11 专属处理:固定窗口居中对齐,明确宽度 attributes?.let { attrs -> attrs.width = WindowManager.LayoutParams.MATCH_PARENT attrs.gravity = Gravity.CENTER attrs.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT attributes = attrs } } } return dialog }
同时确保自定义对话框的布局根视图设置了水平边距,避免内容撑满屏幕:
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginHorizontal="24dp" android:background="@drawable/dialog_background" android:padding="16dp"> <EditText android:id="@+id/input_edit" android:layout_width="0dp" android:layout_height="wrap_content" android:hint="请输入内容" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> <!-- 其他按钮/视图 --> </androidx.constraintlayout.widget.ConstraintLayout>
方法二:监听软键盘状态手动重置位置
通过监听全局布局变化,在软键盘收起时强制重置对话框的居中属性:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val rootView = view.rootView rootView.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { val visibleFrame = Rect() rootView.getWindowVisibleDisplayFrame(visibleFrame) val screenHeight = rootView.rootView.height val keyboardHeight = screenHeight - visibleFrame.bottom // 软键盘已收起时,重置对话框位置 if (keyboardHeight == 0) { dialog?.window?.apply { attributes.gravity = Gravity.CENTER attributes = attributes } } } }) }
问题原因
Android 11系统在处理Dialog窗口与软键盘的交互时,存在一个已知的布局计算Bug:当Dialog未明确指定窗口宽度和对齐方式时,软键盘收起后系统会错误地偏移窗口位置,导致视图右移。通过强制固定窗口参数或手动重置位置,可规避该系统Bug。
内容的提问来源于stack exchange,提问作者Android Leo
相关产品推荐
相关产品推荐

