Fragment中RelativeLayout布局下FloatingActionButton定位错误问题求解
问题根因
你当前使用RelativeLayout作为根布局,但android:layout_gravity属性仅对FrameLayout、LinearLayout、CoordinatorLayout这类父布局生效,RelativeLayout不识别该属性,因此FAB会默认排布在左上角,无法实现右下对齐的效果。
解决方案
方案1:保留RelativeLayout,替换适配的对齐属性
给FAB添加RelativeLayout专属的父布局对齐属性即可,修改后的FAB代码如下:
<com.google.android.material.floatingactionbutton.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" <!-- 替换原来的layout_gravity为以下两个属性 --> android:layout_alignParentBottom="true" android:layout_alignParentEnd="true" android:layout_margin="@dimen/fab_margin" app:srcCompat="@android:drawable/ic_dialog_email" />
如果需要兼容更低版本的RTL布局规则,可以额外添加android:layout_alignParentRight="true"属性。
方案2:更换根布局适配原有属性
如果不想修改FAB的属性,直接把根布局从RelativeLayout换成FrameLayout或者更适合Material组件的CoordinatorLayout即可,原有android:layout_gravity="bottom|end"属性会自动生效。
额外优化建议
你当前给ImageView设置的android:layout_margin="100px"是像素单位,在不同分辨率的设备上显示效果差异很大,建议替换为100dp这类密度无关像素单位,保证多设备适配一致性。
内容的提问来源于stack exchange,提问作者Jodynek
相关产品推荐
相关产品推荐

