Android 踩坑——FloatingActionButton自动添加边距

来源:互联网 发布:清华大学 网络教育 编辑:程序博客网 时间:2024/06/05 06:45

前段时间用android的FloatingActionButton做一个返回顶部的按钮,原本以为挺简单,但是结果有点出乎意料。
布局很简单、

<?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="me.masteryi.trip.MainActivity">    <android.support.design.widget.FloatingActionButton        xmlns:app="http://schemas.android.com/apk/res-auto"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentBottom="true"        android:layout_alignParentRight="true"        android:layout_margin="16dp"        android:src="@drawable/ic_add"        app:fabSize="normal"/></RelativeLayout>

期待的效果是这样的
这里写图片描述

Android5.0以上的手机显示没什么问题,但是在5.0以下显示的边距会大一点
这里写图片描述

打开开发者选项发现,在android5.0以下fab会自动增加边距,而5.0以上则不会

这里写图片描述

所以,解决方案就是增加values-v21文件,在Android5.0以上和以下使用不同边距。
在valuse/dimens.xml中定义5.0以下使用尺寸

<dimen name="action_button_margin">0dp</dimen>

在values-v21/dimens中定义5.0以上使用尺寸

<dimen name="action_button_margin">8dp</dimen>

系统会根据不同系统加载不同dimen

还有,如果fab在CoordinatorLayout中不会出现刚才的问题,android5.0以上跟5.0以下显示效果相同。

0 0