How do I use a floating action button as a square?

2.8k Views Asked by At

There are tons of SO threads saying their button is appearing as a square do to a bug

Floating Action Button with square shape

Square FloatingActionButton with Android Design Library

Floating Action Button appearing as a square

However my goal is to USE a square button. How would I change the circle floating action button into a square one?

<com.google.android.material.floatingactionbutton.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"     
        android:backgroundTint="@color/standardBlue"
        app:srcCompat="@drawable/ic_3d_model"/>
3

There are 3 best solutions below

0
On BEST ANSWER

You can do it with the official FloatingActionButton in the Material Components Library using the shapeAppearanceOverlay attribute.

Just use:

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        app:shapeAppearanceOverlay="@style/fab_square"

with

<style name="fab_square" parent="">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSize">0dp</item>
</style>

enter image description here

0
On

You'd better use this library customFloatingActionButton by Robertlevonyan.

<com.robertlevonyan.examples.customfloatingactionbutton.view.FloatingLayout
        android:id="@+id/floating_layout"
        app:fabType="square"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
1
On

FloatingActionButton does not provide shapes other than rounded see this Request: allow to set the shape of FAB

Yet there are many ways other than this to do But one which I personally recommend is using customFloatingActionButton library by robertlevonyan, It is easy to use and customizable.

Square Shape

Add the following line of code to your module(app) level Gradle file

implementation 'com.robertlevonyan.view:CustomFloatingActionButton:3.0.1'

Now add the following code to activity_main.xml

<com.robertlevonyan.views.customfloatingactionbutton.FloatingActionButton
       android:id="@+id/custom_fab"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_gravity="bottom|end" />

You can customize it in XML too by adding app:fabType="square" but I prefer MainActivity.java

Then customize floatingactionbutton in MainActivity.java

public class MainActivity extends AppCompatActivity {
    private FloatingActionButton floatingActionButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        floatingActionButton = findViewById(R.id.custom_fab);

        floatingActionButton.setFabType(FabType.FAB_TYPE_SQUARE); //set button type to square
        floatingActionButton.setFabIcon(getResources().getDrawable(R.drawable.ic_baseline_add_btn_24, null));

    }
}

Output

enter image description here