如何在XML中按百分比设置Dialog的宽高,使其占屏幕70%空间
问题原因
app:layout_constraintWidth_percent 这类百分比属性要生效,必须满足两个前提:
- 对应方向的尺寸属性(宽对应
layout_width、高对应layout_height)要设置为0dp(即match_constraint) - 对应方向必须同时约束到父布局的两端:宽度需要同时约束左、右贴父布局,高度需要同时约束上、下贴父布局
你原来的根布局宽高设的是wrap_content,也没有加两端约束,所以百分比属性不会生效。
仅修改XML的解决方案
只需要替换根布局的属性即可,子控件代码不需要调整:
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="0dp" android:layout_height="0dp" android:layout_gravity="center" android:background="@drawable/dialog_background_shape" android:padding="@dimen/app_padding" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintWidth_percent="0.7" app:layout_constraintHeight_percent="0.7"> <!-- 此处保留你原来的所有子控件代码即可 --> </androidx.constraintlayout.widget.ConstraintLayout>
补充注意
你当前子控件里写了很多固定宽度(比如250dp、248dp),如果小屏设备下70%的屏幕宽度小于这些固定值,会出现布局溢出,建议也把这些固定宽度改成0dp配合父布局约束做适配。
内容的提问来源于stack exchange,提问作者Roman Knyazev
相关产品推荐
相关产品推荐

