向ImageSpan

时间:2018-01-29 08:43:44

标签: android spannablestring spannable imagespan spannablestringbuilder

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

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

Requirement

这是我尝试过的。

    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());
    }

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

由于

1 个答案:

答案 0 :(得分: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);

对于Kotlin:

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