简体   繁体   中英

How to set background color and underline for an ImageSpan

图片中的编辑文字

As shown above, I have inserted an image into a EditText , with text before and after it. So, I used an ImageSpan .

I wish to change the background color and underline the text dynamically, but I find that it doesn't make effect on the image.

What shall I do to make the ImageSpan show same effect with near text?

I have a partial solution to offer—for the background color. The only way I found to do this (other than writing my own custom span class) is to put the image drawable into a LayerList atop a GradientDrawable that is your background color. In code, it could be something like this:

// Assume that d is the image drawable and bgSpan is the background color span.
// Then instead of doing
//      ImageSpan imgSpan = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
// you do the following:

GradientDrawable gd = new GradientDrawable();
gd.setShape(GradientDrawable.RECTANGLE);
gd.setColor(bgSpan.getBackgroundColor());
LayerDrawable ld = new LayerDrawable(new Drawable[] {gd, d});
ld.setBounds(d.getBounds());
ImageSpan imgSpan = new ImageSpan(ld, ImageSpan.ALIGN_BASELINE);

You might possibly be able to use the same trick to simulate underlining (by adding another drawable to the layer list). However, I haven't experimented with this and can't offer a concrete suggestion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM