Android Spannablecontent With Rounded Corners
android, icons, java
Solution
After reading getting a little help with a converter for C#, I came up with this. I still have some tweaking to do, but if anyone is also looking for a similar answer.
public class RoundedBackgroundSpan extends ReplacementSpan
{
@Override
public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
return 0;
}
@Override
public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint)
{
RectF rect = new RectF(x, top, x + text.length(), bottom);
paint.setColor(Color.CYAN);
canvas.drawRoundRect(rect, 20, 20, paint);
paint.setColor(Color.WHITE);
canvas.drawText(text, start, end, x, y, paint);
}
}
Problem
I am trying to change my string to make a badge with a number in the middle by using Spannable String. I can highlight the appropriate letter/number by setting the BackGroundColorSpan, but need help making it a little prettier. I was hoping to have rounded corners with a little bit of padding around the entire shape. This article is really close to what I'm trying to do: Android SpannableString set background behind part of text I really need to keep the resource as a TextView due to the way it interacts with my application. Any ideas how to utilize ReplacementSpan for my particular situation? Here is my code snippet: ``` if (menuItem.getMenuItemType() == SlidingMenuItem.MenuItemType.NOTIFICATIONS) { myMenuRow.setTypeface(null, Typeface.NORMAL); myMenuRow.setTextColor(getContext().getResources().getColor(R.color.BLACK)); myMenuRow.setActivated(false); SpannableString spannablecontent = new SpannableString(myMenuRow.getText()); spannablecontent.setSpan(new BackgroundColorSpan(Color.argb(150,0,0,0)), 18, myMenuRow.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); myMenuRow.setText(spannablecontent); } ```