如何在Android布局xml文件中定义带下划线的文本?


当前回答

投票最多的答案是正确和最简单的。然而,有时您可能会发现,这不是为某些字体工作,而是为其他字体工作。(这是我在处理中文时遇到的问题。)

解决方案是不要仅对TextView使用“WRAP_CONTENT”,因为没有多余的空间来绘制线条。您可以为TextView设置固定高度,或者使用android:ppaddingVertical和WRAP_CONTENT。

其他回答

你可以试试

textview.setPaintFlags(textview.getPaintFlags() |   Paint.UNDERLINE_TEXT_FLAG);

查看带下划线的可单击按钮样式:

<TextView
    android:id="@+id/btn_some_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/btn_add_contact"
    android:textAllCaps="false"
    android:textColor="#57a0d4"
    style="@style/Widget.AppCompat.Button.Borderless.Colored" />

字符串.xml:

<string name="btn_add_contact"><u>Add new contact</u></string>

结果:

Strings.xml文件内容:

<resource>
     <string name="my_text">This is an <u>underline</u>.</string> 
</resources> 

布局xml文件应使用具有textview以下财产的上述字符串资源,如下所示:

<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:text="@string/my_text"

    android:selectAllOnFocus="false"
    android:linksClickable="false"
    android:autoLink="all"
    />

只需使用字符串资源文件中的属性,例如。

<string name="example"><u>Example</u></string>

另一个解决方案是创建一个扩展TextView的自定义视图,如下所示

public class UnderLineTextView extends TextView {

    public UnderLineTextView(Context context) {
        super(context);
        this.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
    }

    public UnderLineTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
    }

}

并添加到xml,如下所示

<yourpackage.UnderLineTextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="underline text"
 />