2

我正在尝试向图像添加背景跨度。我可以将背景跨度设置为字符串,但同一字符串中的图像跨度不显示背景。

这是我想要的示例,所选部分显示具有背景跨度的图像和文本。

要求

这是我尝试过的。

    public void applySpannable(String lastString, String changeString, int type, String title) {

        String totalString = lastString + title;
        Spannable spanText = new SpannableString(totalString);

        Drawable d;
        if (type == 1) {
            d = getResources().getDrawable(R.drawable.type_flag_bg_red);
        } else {
            d = getResources().getDrawable(R.drawable.type_flag_bg_red);
        }
        d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
        ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);

        ForegroundColorSpan foregroundSpan = new ForegroundColorSpan(Color.WHITE);
        BackgroundColorSpan backgroundSpan = new BackgroundColorSpan(Color.RED);

        spanText.setSpan(foregroundSpan, lowerBound, upperBound, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        spanText.setSpan(backgroundSpan, lowerBound, upperBound, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        spanText.setSpan(span, lastString.length(), lastString.length()+1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);



        edtAddTask.setText(spanText);
        edtAddTask.setSelection(edtAddTask.getText().toString().length());
    }

字符串显示有背景,但透明图像显示没有背景。我已经在图像位置之前设置了较低的索引。

谢谢

4

1 回答 1

0

您不能同时使用 BackgroundColorSpan 和 ImageSpan。这个想法是从带有背景和图像层的LayerDrawable创建一个 ImageSpan 。请看下面的代码:

试试这个java:

Spannable span = new SpannableString("This is   ic launcher with background");
Drawable myImage = context.getResources().getDrawable(R.drawable.ic_launcher_foreground);
ShapeDrawable background = new ShapeDrawable();
background.getPaint().setColor(Color.RED);
LayerDrawable layerDrawable = new LayerDrawable(new Drawable[]{background, myImage});
layerDrawable.setBounds(0, 0, 64, 64);
ImageSpan image = new ImageSpan(layerDrawable, ImageSpan.ALIGN_BASELINE);
span.setSpan(image, 8, 9, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

textView.setText(span);

对于科特林:

val span: Spannable = SpannableString("This is   ic launcher with background")
val myImage: Drawable = resources.getDrawable(R.drawable.ic_launcher_foreground)
val background = ShapeDrawable()
background.paint.color = Color.RED
val layerDrawable = LayerDrawable(arrayOf(background, myImage))
layerDrawable.setBounds(0, 0, 64, 64)
val image = ImageSpan(layerDrawable, ImageSpan.ALIGN_BASELINE)
span.setSpan(image, 8, 9, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)

textView.setText(span)

从这个答案:https ://stackoverflow.com/a/60150320/6160172

于 2020-02-17T04:48:54.710 回答