2

Is there a way to underline the text in a Button using a style? I can do it by wrapping the text in strings.xml with html tags like this

<string name="my_text"><u>My underlined text</u></string>

But I rather have it like this

<com.google.android.material.button.MaterialButton
    style="@style/Widget.MaterialComponents.Button.TextButton"
    android:id="@+id/my_button"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    <!-- not working --> android:textStyle="underline"
    android:text="@string/my_text" />

and ideally I would define the style in styles.xml

<style name="MyButton" parent="Widget.MaterialComponents.Button.TextButton">
    <!-- not working --><item name="android:textStyle">underline</item>
</style>

And I know I could probably make my own custom Button that will have the text underlined. But that feels like it would take a lot of effort for something so basic.

Edit My question was marked as possible duplicate for this question, but I'm trying to achieve underlining via styling.

Phantômaxx
  • 37,352
  • 21
  • 80
  • 110
Wirling
  • 4,085
  • 2
  • 40
  • 70

2 Answers2

4

Unfortunately, there is only those two ways

  • using <u> </u>
  • button.setPaintFlags(button.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
Amjad Alwareh
  • 2,517
  • 21
  • 24
2

You can't define it with a style (underline doesn't exist).
Just use:

MaterialButton button = findViewById(R.id.xxxxx);
button.setPaintFlags(button.getPaintFlags() |   Paint.UNDERLINE_TEXT_FLAG);

enter image description here

Gabriele Mariotti
  • 250,295
  • 77
  • 670
  • 690