How to center image in FloatingActionButton behind transparent background?

Murat picture Murat · May 22, 2017 · Viewed 12.8k times · Source

I have a FloatingActionButton and I would like to make it transparent with a centered icon.

I added a style:

<style name="ButtonTransparent">
    <item name="colorAccent">@android:color/transparent</item>
</style>

which works so far. THe FAB got transparent. Then I added the FAB :

<?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"
    android:orientation="vertical"
    tools:context=".activities.CameraActivity">
    <TextureView
        android:id="@+id/texture"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true">

        <ImageView
            android:id="@+id/iv_last_image"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_gravity="center_horizontal"
            android:layout_margin="10dp" />

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/btn_takepicture"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_gravity="center_horizontal"
            android:layout_margin="20dp"
            android:theme="@style/ButtonTransparent"
            android:src="@drawable/selector_vector_camera_light" />

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/btn_back"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_gravity="center_horizontal"
            android:layout_margin="20dp"
            android:theme="@style/ButtonTransparent"
            android:src="@drawable/selector_vector_go_back" />
    </LinearLayout>
</RelativeLayout>

but as you can see on the screenshot below it is not well aligned. How can I correct that? screenshot

Answer

Aayush Singla picture Aayush Singla · Jul 22, 2018

Use this attribute: fab:fabCustomSize="100dp" make this equal to height and width of your fab. This helped me.This was my code.

<com.google.android.material.floatingactionbutton.FloatingActionButton
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="60dp"
    android:layout_height="60dp"
    app:fabCustomSize="60dp"
    android:backgroundTint="@color/colorPrimary"
    android:src="@drawable/ic_insert_drive_file_24dp" />

Another way could be using android:foreground attribute instead of src and then setting android:foreground_gravity to center.