How to underline text of button in Android?

2019-03-09 02:50发布

I am new in android programming.I am developing a simple app . I have a button which is transparent and has an icon and text. I want to underline the text of the button but i have not been able to do this. Below is my xml code:

<Button
 android:id="@+id/park"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:drawableLeft="@drawable/park"
 android:text="@string/button_name"
 android:background="#00000000"
 android:textColor="#000000"/>

And the string file has:

<resources>

 <string name="button_name"><u>parking areas</u></string>
</resources

This approa ch works in textview but not in button.

-any suggestion?

5条回答
你好瞎i
2楼-- · 2019-03-09 02:51

This should make your ButtonText bold, underlined and italic at the same time.

strings.xml

<resources>
    <string name="register"><u><b><i>Copyright</i></b></u></string>
</resources>

To set this String to your TextView, do this in your main.xml

<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/btn1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:text="@string/register" />
查看更多
该账号已被封号
3楼-- · 2019-03-09 02:52

Code only

Java:

Button button = (Button) findViewById(R.id.park);
button.setPaintFlags(button.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

Kotlin:

val button = findViewById<Button>(R.id.park);
button.paintFlags = button.paintFlags or Paint.UNDERLINE_TEXT_FLAG

Resource string with static text (xml only)

If you have a static text in your resources you could also use the following approach in your strings.xml:

<string name="underlined_text"><u>I\'m underlined</u></string>

Resource string with dynamic text (xml + code)

If you're using dynamic text but don't like the first approach (which isn't the best imho either), you could also use following:

strings.xml

<string name="underlined_dynamic_text"><u>%s</u></string>

Java:

button.setText(getString(R.string.underlined_dynamic_text, "I'm underlined");

Kotlin:

button.text = getString(R.string.underlined_dynamic_text, "I'm underlined")
查看更多
smile是对你的礼貌
4楼-- · 2019-03-09 03:02
Button button= (Button) findViewById(R.id.park);
SpannableString content = new SpannableString("Content");
content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
button.setText(content);
查看更多
在下西门庆
5楼-- · 2019-03-09 03:06

Use this:

TextView txt=(TextView)findViewById(R.id.txt);
        String styledText = "<u>parking areas</u>";
        txt.setText(Html.fromHtml(styledText), TextView.BufferType.SPANNABLE);
查看更多
Bombasti
6楼-- · 2019-03-09 03:12

You can't set underline from xml file. To set underline using code you need to set the underline flag on button.

Button button = (Button) findViewById(R.id.park);
button.setPaintFlags(button.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
查看更多
登录 后发表回答