我正在尝试向图像添加背景范围。我可以将背景范围设置为字符串,但是同一字符串中的imagespan不会显示背景。
这是我想要的示例,所选部分显示具有背景跨度的图像和文本。
这是我尝试过的。
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());
}
字符串以背景显示,但是透明图像显示为没有背景。我已经将较低的索引设置在图像位置的前面。
谢谢
您不能同时使用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)