如何在Android布局xml文件中定义带下划线的文本?
当前回答
如果要在XML中实现这一点,请在resource中声明字符串,并将该资源值放入HTML的下划线标记(<u></u>)中。在TextView中,添加
android:text="@string/your_text_reference"
在字符串资源值中,
<string name="your_text_reference"><u>Underline me</u></string>
如果您想以编程方式实现这一点,请使用Kotlin
textView.paintFlags = textView.paintFlags or Paint.UNDERLINE_TEXT_FLAG
or,
textView.text = Html.fromHtml("<p><u>Underline me</u></p>")
其他回答
罗曼·盖伊(Romain Guy)用GitHub上的可用源代码描述了最新的画下划线文本的方法。此示例应用程序公开了两种可能的实现:
需要API级别19的基于路径的实现需要API级别1的基于区域的实现
另一个解决方案是创建一个扩展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"
/>
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"
/>
我使用这个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>
转到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
我希望这有帮助。
推荐文章
- 我如何在一个片段中访问getSupportFragmentManager() ?
- 调试在哪里。Android Studio中的密钥存储库
- 从资产中读取文件
- 在不活动的地方调用getLayoutInflater()
- 设置Android布局元素的背景颜色
- 错误:'keytool'不能被识别为内部或外部命令、可操作程序或批处理文件
- 在应用程序本身中更改Locale
- apk (.apk)和应用程序包(.aab)的区别
- 如何设置超时在改造库?
- Android - SPAN_EXCLUSIVE_EXCLUSIVE跨度不能为零长度
- TextView的字体大小在Android应用程序改变字体大小从本机设置
- 如何模拟Android杀死我的进程
- 禁用EditText闪烁光标
- Android Eclipse -无法找到*.apk
- 设置TextView文本从html格式的字符串资源在XML