36
34

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

DesignSupportLibraryのFABがAPI21以上と未満でmarginが違う問題の対処法

Posted at

com.android.support:design:22.2.0 時点での情報です。今後のアップデートで修正されるかもしれません。

現象

Lolipop以降の端末とLolipop未満の端末で、FABのmarginの大きさが変わります。

こんな感じのレイアウトを組むと、Lolipop以降は16dpのmarginで表示されますが、Lolipop未満は32dp、24dpのmarginで表示されてしまいます。

<android.support.design.widget.FloatingActionButton
    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_plus_white_24dp"
    app:borderWidth="0dp" />

2015-07-07_13_38_32_png_と_2015-07-07_13_40_38_png.png

原因

Lolipop未満の場合、 elevation が使えないため、DesignSupportLibraryの中の ShadowDrawableWrapper というクラスでShadowを表現しています。

FloatingActionButtonの実処理を行っているFloatingActionButtonEclairMr1を見るとわかりますが、Shadow部分が上下左右にそれぞれ8dp、16dp、8dp、8dp取っています。

そのため、FloatingActionButton自体にmarginをつけてしまうとShadow部分のmargin分余白が大きくなってしまうわけです。

対処方法

コード内でバージョンごとに分岐してmarginを動的にセットしてもできるのですが、 values-v21のリソースフォルダを使って対応した方がスマートに解決できます。

values-v21/styles.xml

<style name="FabMargin">
    <item name="android:layout_margin">16dp</item>
</style>

values/styles.xml

<style name="FabMargin">
    <item name="android:layout_marginLeft">8dp</item>
    <item name="android:layout_marginTop">8dp</item>
    <item name="android:layout_marginRight">8dp</item>
    <item name="android:layout_marginBottom">0dp</item>
</style>

layouts

<android.support.design.widget.FloatingActionButton
    style="@style/FabMargin"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:src="@drawable/ic_plus_white_24dp"
    app:borderWidth="0dp" />

おそらく今後のバージョンアップで修正されると思うので、修正後はstyleを消して layout_margin に書き換えればいいと思います。

36
34
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
36
34

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?