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


当前回答

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

其他回答

     <com.google.android.material.textfield.TextInputEditText
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:backgroundTint="@android:color/transparent"
                    android:hint="@string/search_url"
                    android:textColor="@color/coffee_color"
                    android:textColorHint="@color/coffee_color"
                    />

转到strings.xml资源文件必要时,在资源文件中添加带有HTML下划线标记的字符串。

strings.xml HTML下划线示例

按如下方式调用Java代码中的字符串资源ID:

sampleTextView.setText(R.string.sample_string);

输出应带有下划线的单词“Stacksoverflow”。

此外,以下代码不会打印下划线:

String sampleString = getString(R.string.sample_string);
sampleTextView.setText(sampleString);

相反,使用以下代码保留RTF格式:

CharSequence sampleString = getText(R.string.sample_string);
sampleTextView.setText(sampleString);

“您可以使用getString(int)或getText(int)来检索字符串。getText(int)保留应用于字符串的任何富文本样式。”Android文档。

请参阅文档:https://developer.android.com/guide/topics/resources/string-resource.html

我希望这有帮助。

尝试此代码

XML格式

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

在代码中

TextView textView = (TextView) view.findViewById(R.id.textview);
textView.setText(Html.fromHtml(getString(R.string.my_text)));

祝你好运

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

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

如果您使用的是字符串资源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);