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


当前回答

我简化了塞缪尔的回答:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <!--https://stackoverflow.com/a/40706098/4726718-->
    <item
        android:left="-5dp"
        android:right="-5dp"
        android:top="-5dp">
        <shape>
            <stroke
                android:width="1.5dp"
                android:color="@color/colorAccent" />
        </shape>
    </item>
</layer-list>

其他回答

对于Button和TextView,这是最简单的方法:

按钮:

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

文本视图:

TextView textView = (TextView) findViewById(R.id.textview1);
textView.setPaintFlags(textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

在Kotlin中可以使用扩展函数。这只能从代码中使用,而不能从xml中使用。

fun TextView.underline() {
    paintFlags = paintFlags or Paint.UNDERLINE_TEXT_FLAG
}

用法:

 tv_change_number.underline()
 tv_resend_otp.underline()

我在使用自定义字体时遇到了一个问题,使用资源文件技巧(<u>下划线文本</u>)创建的下划线确实有效,但Android成功地将下划线转换成了一种罢工槽。

我用这个答案在文本视图下面画了一个边框:https://stackoverflow.com/a/10732993/664449.显然,这对于部分下划线文本或多行文本不起作用。

罗曼·盖伊(Romain Guy)用GitHub上的可用源代码描述了最新的画下划线文本的方法。此示例应用程序公开了两种可能的实现:

需要API级别19的基于路径的实现需要API级别1的基于区域的实现

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"
    />