Search code examples
androidmaterial-designandroid-buttonmaterial-components-androidmaterial-components

How to change a button shape style at runtime?


I am developing an app in java, android studio, where the user can choose the style color of the app.

With most components just use the .setBackground(colorUser);

The problem is in my buttons.

My buttons are all rounded, I created a shape for that.

My shape is in other file...

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="10dp"
    android:shape="rectangle">

    <solid android:color="@color/colorJetway" />

    <corners
        android:bottomLeftRadius="80dp"
        android:bottomRightRadius="80dp"
        android:topLeftRadius="80dp"
        android:topRightRadius="80dp" />

</shape>

<Button
            android:id="@+id/btnAdc"
            android:layout_width="84dp"
            android:layout_height="84dp"
            android:layout_marginTop="12dp"

            android:layout_marginEnd="205dp"
            android:background="@drawable/btns_border"
            android:onClick="btnAdicionar_click"
            android:text="+"
            android:textColor="#FFFFFF"
            android:textSize="40dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/txtQuantidade" />

That way if at runtime I make mybutton.setBackground(colorUser) my button loses its style ... it will have no rounded edges.

How can I do it?


Solution

  • It is not exactly what you are looking for.
    However using the MaterialButton component it is very simple to have rounded buttons.

    Just use app:cornerRadius to define the corner radius and app:backgroundTint to change the background color.

    <com.google.android.material.button.MaterialButton
        app:backgroundTint="@color/myselector"
        app:cornerRadius="xxdp"
        .../>
    

    You can programmatically change these values using:

    button.setCornerRadius(...);
    button.setBackgroundTintList(..);