Search code examples
androidandroid-layoutmaterial-designandroid-buttonandroidx

Programmatically create a MaterialButton with Outline style


I would programmatically like to create a button as defined in the design guidelines here: https://material.io/design/components/buttons.html#outlined-button, looking like this:

enter image description here

In XML I'm able to do this, using this piece of layout xml:

<com.google.android.material.button.MaterialButton
    android:id="@+id/buttonGetStarted"
    style="@style/Widget.MaterialComponents.Button.OutlinedButton"
    android:text="@string/title_short_intro" />

What I'm looking for is an example that shows how to do this using Java code? I have tried the following:

MaterialButton testSignIn = new MaterialButton( new ContextThemeWrapper( this, R.style.Widget_MaterialComponents_Button_OutlinedButton));
String buttonText = "Sign-in & empty test account";
testSignIn.setText( buttonText );

But this does not result in the outline variant:

enter image description here


Solution

  • You can use below:

    MaterialButton testSignIn = new MaterialButton(context, null, R.attr.borderlessButtonStyle);
    String buttonText = "Sign-in & empty test account";
    testSignIn.setText(buttonText);