我正在尝试创建一个跨度来为文本提供圆角背景。但是,永远不会调用draw
方法。
这是代码:
public class RoundedBackgroundSpan extends ReplacementSpan {
@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 + measureText(paint, text, start, end), bottom);
paint.setColor(Color.BLUE);
canvas.drawRoundRect(rect, 100f, 30f, paint);
paint.setColor(Color.WHITE);
canvas.drawText(text, start, end, x, y, paint);
}
@Override
public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm)
{
return Math.round(measureText(paint, text, start, end));
}
private float measureText(Paint paint, CharSequence text, int start, int end)
{
return paint.measureText(text, start, end);
}
}
这就是我设置它的方式:
Spannable spannable = new SpannableString(introText.getText());
spannable.setSpan(new RoundedBackgroundSpan(), 0, textView.getText().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannable);
我不知道为什么这不起作用。
答案 0 :(得分:0)
创建shapes.xml,如下所示
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF" />
<stroke android:width="1dp" android:color="#000000" />
<padding android:left="1dp" android:top="1dp" android:right="1dp"
android:bottom="1dp" />
<corners
android:bottomRightRadius="15dp"
android:bottomLeftRadius="15dp"
android:topLeftRadius="15dp"
android:topRightRadius="15dp"/>
</shape>
在你的xml文件中,使用android:background =“@ drawable / shapes”作为文本。