0

TextView のテキストをしっかりと囲む背景を作成する @TangXianQiang の助けのおかげで、次のコードがあります。

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

結果: ここに画像の説明を入力

ただし、この背景の内側に 8 dp のパディングを追加して、テキストの端がきつくならないようにしたいと思います。文字列ビルダーは文字列の最初と最後でしか機能しないので、どうすればこれを達成できますか?

4

0 に答える 0