在 TextView 中的多行文本背景中紧紧包裹间隙

Tightly wrap gaps in background of multiple lines of text in TextView

我已经编写了 XML 代码来显示具有绿色背景的 TextView:

但是,我希望第二行文本左右两侧的 space 完全透明,没有任何绿色背景 -- 通常环绕更靠近文本。

这是一张图片,描绘了左侧应该透明的部分(尽管我打算两边都是透明的)。

现在我知道我可以通过使用两个 TextView 并在两个视图之间拆分 Java 代码中的文本来实现此目的。因为它们是分开的,所以它们会各自换行,因此底部视图上的文本会被紧紧地换行,而不是 affected/expanded 被顶部视图换行。

但是,理想情况下,我想在 XML 中或使用更优雅的解决方案来执行此操作。这可以用 XML 完成吗?还是我需要坚持使用我提出的使用多个 TextView 的解决方案?

你以前知道Graphic Text Mixed吗?此代码将帮助您:

String str="this bit of text spans more than one line.Words words words";
    int bstart=0;
    int bend=str.length();

    SpannableStringBuilder style=new SpannableStringBuilder(str);
    style.setSpan(new BackgroundColorSpan(ContextCompat.getColor(this,R.color.colorGreenTra)),bstart,bend, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    TextView tvColor=(TextView) findViewById(R.id.tv_color);
    tvColor.setText(style);

在XML中:

<TextView
    android:id="@+id/tv_color"
    android:layout_width="280dp"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:text="this bit of text spans more than one line.Words words words"
    />

效果: