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


当前回答

我使用这个xml可绘制文件来创建底部边框,并将可绘制文件作为背景应用到文本视图中

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle" >
            <solid android:color="@android:color/transparent" />
        </shape>
    </item>

    <item android:top="-5dp" android:right="-5dp" android:left="-5dp">
        <shape>
            <solid android:color="@android:color/transparent" />
            <stroke
                    android:width="1.5dp"
                    android:color="@color/pure_white" />
        </shape>
    </item>
</layer-list>

其他回答

如果您使用的是字符串资源xml文件,该文件支持HTML标记,如<b></b>、<i></i>和<u></u>,则可以实现这一点。

<resources>
    <string name="your_string_here"><![CDATA[This is an <u>underline</u>.]]></string>
</resources>

如果您想在代码中添加下划线,请使用:

TextView textView = (TextView) view.findViewById(R.id.textview);
SpannableString content = new SpannableString("Content");
content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
textView.setText(content);

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

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

结果:

另一个解决方案是创建一个扩展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"
 />

要在Kotlin做到这一点:

你的TextView.praint?。isUnderlineText=真

非常紧凑的科特林版本:

tvTitle.apply { 
    text = "foobar"
    paint?.isUnderlineText = true
}