android - android中spanableString的背景颜色

标签 android textview

我只使用一个 TextView 并使用 spanable 向字符串添加字体和颜色。但是我在使用 spanable 将圆形背景显示为字符串时遇到问题。那么我如何使用 spannable String 概念实现这一点,图像如下所示。

enter image description here

最佳答案

对于 TextView 的背景颜色,您可以使用

String myString = "myString";
Spannable spanna = new SpannableString(myString);
spanna.setSpan(new BackgroundColorSpan(0xFFCCCCCC),0, myString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);           
myTextView.setText(spanna);

并为圆形 TextView 创建自定义 XML 并为该 TextView 设置背景。

编辑

创建一个名为 rounded_corner.xml 的 XML 并设置此内容

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <!-- view background color -->
    <solid android:color="#ffffff" >
    </solid>

    <!-- view border color and width -->
    <stroke
        android:width="1dp"
        android:color="#1c1b20" >
    </stroke>

    <!-- If you want to add some padding -->
    <padding
        android:bottom="4dp"
        android:left="4dp"
        android:right="4dp"
        android:top="4dp" >
    </padding>

    <!-- Here is the corner radius -->
    <corners android:radius="10dp" >
    </corners>

</shape>

然后将这一行添加到您的 XML TextView 中

android:background="@drawable/rounded_corner"

关于android - android中spanableString的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25724117/

相关文章:

android phonegap 应用程序

android - Recyclerview - 如何在项目滑动时禁用垂直滚动 (fling)

android - Android Studio Gradle构建错误:不允许字符串类型(在 'activity_horizontal_margin'处,值为 '')

Android textView.setText() 崩溃应用

android - Android EditText(TextView)如何绘制闪烁的光标?

android - 消息gradle中此错误的含义是什么,如何解决?

android - 如何使用 android/busybox shell 命令删除指定文件的所有符号链接(symbolic link)?

java - 如何使用Paint.getTextBounds()快速获取TextView的宽高?

java - 通过括号转换为字符串会导致 Android 崩溃

android - 如何设置 TextView 颜色与角度的渐变?