如何实现双按钮各占50%高度的自适应布局?兼容多设备尺寸
实现两个各占50%高度的按钮布局
可行性与兼容性
- 完全可以实现这种两个按钮各占父布局50%高度的布局,而且通过合适的布局方式,能完美适配从手机到平板的各种不同尺寸设备,不用担心适配问题。
推荐实现方案:ConstraintLayout + Guideline
你找到的这个方案真的很靠谱!ConstraintLayout本身就是为灵活适配各种屏幕场景设计的,用Guideline来划分高度区域,能精准控制按钮的占比,还能轻松实现TextView覆盖按钮的效果,具体实现步骤和示例如下:
实现步骤
- 添加水平Guideline:创建一个水平方向的Guideline,通过
app:layout_constraintGuide_percent="0.5"把父布局垂直划分为上下各50%的区域。 - 约束两个按钮:
- 上方按钮:顶部对齐父布局顶部,底部绑定到Guideline,左右铺满父布局,高度设为
0dp让ConstraintLayout自动计算。 - 下方按钮:顶部绑定到Guideline,底部对齐父布局底部,同样左右铺满、高度设为
0dp。
- 上方按钮:顶部对齐父布局顶部,底部绑定到Guideline,左右铺满父布局,高度设为
- 添加覆盖的TextView:把TextView放在ConstraintLayout中,通过约束定位到需要覆盖的位置(比如居中),由于ConstraintLayout的渲染层级是按xml编写顺序来的,把TextView写在按钮之后,就能自动覆盖在按钮上方。
完整示例代码
<?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" android:layout_width="match_parent" android:layout_height="match_parent"> <!-- 上半部分按钮:占父布局50%高度 --> <Button android:id="@+id/btn_upper" android:layout_width="match_parent" android:layout_height="0dp" android:text="上半区按钮" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toTopOf="@id/horizontal_guideline" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent"/> <!-- 水平Guideline:划分50%高度节点 --> <androidx.constraintlayout.widget.Guideline android:id="@+id/horizontal_guideline" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" app:layout_constraintGuide_percent="0.5"/> <!-- 下半部分按钮:占父布局50%高度 --> <Button android:id="@+id/btn_lower" android:layout_width="match_parent" android:layout_height="0dp" android:text="下半区按钮" app:layout_constraintTop_toBottomOf="@id/horizontal_guideline" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent"/> <!-- 覆盖在按钮上的TextView --> <TextView android:id="@+id/tv_overlay" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="我是覆盖文本" android:textSize="22sp" android:textColor="#FFFFFF" android:padding="8dp" android:background="#80000000" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent"/> </androidx.constraintlayout.widget.ConstraintLayout>
兼容性说明
这个方案的兼容性拉满:ConstraintLayout属于Android Jetpack组件,支持API Level 14及以上的设备,几乎覆盖了所有正在使用的Android设备。而且通过百分比设置Guideline,不管屏幕是长屏、短屏还是平板的大屏,两个按钮都会自动占据各自的50%高度,完美适配各种尺寸。
内容的提问来源于stack exchange,提问作者Scar
相关产品推荐
相关产品推荐

