Denis Steinman
Denis Steinman

Reputation: 7799

Incorrect FloatingActionButton layout margins on Android that's below 5.0

Cannot understand why my floating action button has margin like 32dp instead 16dp?

<android.support.design.widget.FloatingActionButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/fab"
    android:src="@drawable/ic_add_24"
    android:layout_gravity="bottom|end"
    android:layout_marginRight="16dp"
    android:layout_marginEnd="16dp"
    android:layout_marginBottom="16dp"/>

On Android 5.0 (emulator) all is correct but on Android 4.3 (real device) margins is too large. Although root layout hasn't paddings or margins.
P.S. FloatActionButton from Google design library.

Android 4.3 Screenshot

Upvotes: 1

Views: 519

Answers (1)

Farouk Touzi
Farouk Touzi

Reputation: 3456

The only way apparently to achieve this, is using a an API-specific styles. In your normal values/styles.xml, put something like this:

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

Then under values-v21/styles.xml, use this:

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

Finally, apply the style to your FloatingActionButton :

<android.support.design.widget.FloatingActionButton
...
style="@style/floating_action_button"
...
/>

As Zielony have noted, in API <20, the button renders its own shadow, which adds to the overall logical width of the view, whereas in API >=20 it uses the new Elevation parameters which don't contribute to the view width.

Upvotes: 2

Related Questions