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

问题描述 投票:0回答:1

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

enter image description here

但是,我希望第二行文本左侧和右侧的空间完全透明,没有任何绿色背景 - 通常更接近文本。

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

enter image description here

现在我知道我可以通过使用两个放在彼此上面的TextView并在两个视图之间拆分Java代码中的文本来实现这一点。由于它们是分开的,因此它们每个都会换行,因此底部视图上的文本将被紧紧包裹,而不会被顶部视图的包裹影响/扩展。

但是,理想情况下,我想在XML中使用更优雅的解决方案。这可以用XML完成,还是我需要坚持使用我提出的使用多个TextViews的解决方案?

android xml android-layout textview android-xml
1个回答
1
投票

你知道之前的图形文字混合吗?此代码将帮助您:

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"
    />

效果:enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.