Programmatically create a MaterialButton with Outline style

Viewed 6670

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

4 Answers

You can use below:

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

If you want to apply a Outlined button you can use the R.attr.materialButtonOutlinedStyle attribute style in the constructor:

MaterialButton outlinedButton = new MaterialButton(context,null, R.attr.materialButtonOutlinedStyle);
outlinedButton.setText("....");

enter image description here

MaterialButton has strokeColor and strokeWidth which is used to set the outline.

val _strokeColor = getColorStateList(R.styleable.xxx_strokeColor)
val _strokeWidth = getDimensionPixelSize(R.styleable.xxx_strokeWidth, 0)

button = MaterialButton(context).apply {
    layoutParams = LayoutParams(MATCH_PARENT, WRAP_PARENT)
    strokeColor = _strokeColor
    strokeWidth = _strokeWidth
}

Create outlined button layout outlined_button.xml

<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.button.MaterialButton xmlns:android="http://schemas.android.com/apk/res/android"
    style="@style/Widget.MaterialComponents.Button.OutlinedButton"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</com.google.android.material.button.MaterialButton>

Then inflate outlined button in runtime

LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
MaterialButton button = (MaterialButton)inflater.inflate(R.layout.outlined_button, vg, false);
Related