如何在Android布局xml文件中定义带下划线的文本?
当前回答
如果您使用的是字符串资源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);
其他回答
<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"
/>
上面的“接受”答案不起作用(当您尝试使用textView.setText(Html.fromHtml(string.format(getString(…),…)))这样的字符串时)。
如文档中所述,您必须用<;,例如,结果应如下所示:
<resource>
<string name="your_string_here">This is an <u>underline</u>.</string>
</resources>
然后在代码中,您可以使用以下选项设置文本:
TextView textView = (TextView) view.findViewById(R.id.textview);
textView.setText(Html.fromHtml(String.format(getString(R.string.my_string), ...)));
我简化了塞缪尔的回答:
<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>
在Kotlin中可以使用扩展函数。这只能从代码中使用,而不能从xml中使用。
fun TextView.underline() {
paintFlags = paintFlags or Paint.UNDERLINE_TEXT_FLAG
}
用法:
tv_change_number.underline()
tv_resend_otp.underline()
我使用这个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>
推荐文章
- 有没有办法自动安装Android SDK ?
- 如何检查一个视图在Android中是否可见?
- Android是否保留。apk文件?如果有,在哪里?
- 在Android 5棒棒糖中,通知栏图标变成白色
- 从URI获取真实路径,Android奇巧新的存储访问框架
- 如何检查JSON键是否存在?
- ImageView -有高度匹配宽度?
- 如何确定在android文件的MIME类型?
- 这是在Android中获取用户位置的好方法
- Android从左到右幻灯片动画
- 如何检索视图的维度?
- 如何改变菜单项的文本颜色在安卓?
- Android选择器和文本颜色
- 视图绑定-我如何获得包含布局的绑定?
- 在Android Studio中改变矢量资产的填充颜色