如何在Android布局xml文件中定义带下划线的文本?
当前回答
非常紧凑的科特林版本:
tvTitle.apply {
text = "foobar"
paint?.isUnderlineText = true
}
其他回答
最简单的方法
TextView tv = findViewById(R.id.tv);
tv.setText("some text");
setUnderLineText(tv, "some");
还支持TextView子项,如EditText、Button、Checkbox
public void setUnderLineText(TextView tv, String textToUnderLine) {
String tvt = tv.getText().toString();
int ofe = tvt.indexOf(textToUnderLine, 0);
UnderlineSpan underlineSpan = new UnderlineSpan();
SpannableString wordToSpan = new SpannableString(tv.getText());
for (int ofs = 0; ofs < tvt.length() && ofe != -1; ofs = ofe + 1) {
ofe = tvt.indexOf(textToUnderLine, ofs);
if (ofe == -1)
break;
else {
wordToSpan.setSpan(underlineSpan, ofe, ofe + textToUnderLine.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(wordToSpan, TextView.BufferType.SPANNABLE);
}
}
}
如果你愿意
-可单击下划线文本?
-给TextView的多个部分加下划线?
然后检查此答案
尝试此代码
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)));
祝你好运
如果您使用的是字符串资源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);
要在Kotlin做到这一点:
你的TextView.praint?。isUnderlineText=真
我简化了塞缪尔的回答:
<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>
推荐文章
- 我如何在一个片段中访问getSupportFragmentManager() ?
- 调试在哪里。Android Studio中的密钥存储库
- 从资产中读取文件
- 在不活动的地方调用getLayoutInflater()
- 设置Android布局元素的背景颜色
- 错误:'keytool'不能被识别为内部或外部命令、可操作程序或批处理文件
- 在应用程序本身中更改Locale
- apk (.apk)和应用程序包(.aab)的区别
- 如何设置超时在改造库?
- Android - SPAN_EXCLUSIVE_EXCLUSIVE跨度不能为零长度
- TextView的字体大小在Android应用程序改变字体大小从本机设置
- 如何模拟Android杀死我的进程
- 禁用EditText闪烁光标
- Android Eclipse -无法找到*.apk
- 设置TextView文本从html格式的字符串资源在XML