RelativeLayout中FloatingActionButton跨设备位置偏移问题求助
你现在遇到的问题核心是用固定dp值的layout_marginTop和layout_marginLeft做绝对定位——这种方式完全忽略了不同设备的屏幕尺寸、密度差异,自然会出现预览和真机不一致、切换设备位置偏移的情况。而且android:gravity在这里根本不起作用,因为它是用来控制View内部内容的对齐方式,不是控制View自身在父布局中的位置。
正确的做法:用RelativeLayout的相对对齐属性定位
RelativeLayout的核心就是通过相对位置来布局子View,你应该用它的专属对齐属性来固定FAB的位置,而不是硬写margin数值。比如如果想把FAB放在右下角(Material Design推荐的FAB位置),可以这么修改你的FAB代码:
<android.support.design.widget.FloatingActionButton android:id="@+id/floorActionButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentEnd="true" android:layout_marginBottom="16dp" android:layout_marginEnd="16dp" app:backgroundTint="@color/primaryColor" app:fabSize="normal" android:src="@drawable/ic_action_calendar"/>
代码解释:
android:layout_alignParentBottom="true":让FAB紧贴RelativeLayout的底部边缘android:layout_alignParentEnd="true":让FAB紧贴RelativeLayout的右侧边缘(如果是旧版本SDK,可以用android:layout_alignParentRight="true")- 用小数值的
layout_marginBottom和layout_marginEnd(比如Material Design推荐的16dp)来给FAB和屏幕边缘留一个合适的间距,而不是用430dp、300dp这种固定的大数值
这样修改后,不管是编辑器预览还是实际设备,不管屏幕大小如何,FAB都会稳定地出现在右下角,不会出现偏移问题。
额外提醒:
如果你需要把FAB放在其他相对位置(比如相对于RecyclerView的某个位置),也可以用RelativeLayout的layout_above、layout_toStartOf等属性,始终遵循相对定位的原则,避免用固定的margin值来做绝对位置的布局。
内容的提问来源于stack exchange,提问作者Vladimír Fencák
相关产品推荐
相关产品推荐

