RelativeLayout布局下按钮多机型位置不一致,如何修改代码
安卓多机型按钮位置偏移解决方案
- 问题核心原因
- 三个按钮单独对齐父布局底部,其中“Paylaş”按钮使用硬编码
layout_marginEnd="140dp"定位,不同机型屏幕宽度不同,该固定dp值对应的相对位置存在差异 - 按钮使用
wrap_content宽度,未统一纳入水平排列容器,无法适配不同屏幕尺寸
- 三个按钮单独对齐父布局底部,其中“Paylaş”按钮使用硬编码
- 调整方案
- 新增水平方向
LinearLayout作为底部按钮容器,统一对齐父布局底部,设置统一的底部、左右边距 - 取消所有按钮单独对齐父布局的属性,将三个按钮放入容器内水平排列,通过权重分配宽度,保证相对位置在所有机型上一致
- 新增水平方向
- 修改后完整布局代码
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:background="@drawable/v" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_marginStart="20dp" android:layout_marginEnd="20dp" android:layout_marginBottom="60dp" android:orientation="horizontal" android:gravity="center_vertical"> <Button android:id="@+id/btn1" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:background="@drawable/y" android:text="Değiştir" android:textColor="#ffffff" android:textSize="15dp" android:onClick="random"/> <Button android:id="@+id/button" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:background="@drawable/y" android:text="Paylaş" android:textColor="#ffffff" android:textSize="15dp" android:onClick="paylas"/> <Button android:id="@+id/btn2" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:background="@drawable/y" android:text="Kopyala" android:textColor="#ffffff" android:textSize="15dp" android:onClick="kopyala"/> </LinearLayout> </RelativeLayout>
- 补充说明
- 若需要调整三个按钮的间距,可给按钮设置
layout_marginHorizontal属性,权重分配的相对位置不会受影响 - 原硬编码的固定偏移属性已全部移除,不会再随屏幕宽度变化出现位置偏移
- 若需要调整三个按钮的间距,可给按钮设置
内容的提问来源于stack exchange,提问作者eqwecom
相关产品推荐
相关产品推荐

