目前,我有一个SpannableString对象,其中设置了多个Clickable对象。因此,一个字符串包含许多Clickable对象,并且取决于用户单击应用程序的哪个单词/部分,应用程序将继续运行并处理该click事件。几天前,我在stackoverflow上问过要摆脱SpannableString中单词的蓝色下划线的问题,答案是对ClickableSpan类进行子类化,并覆盖updateDrawState方法并将underlineText设置为false起作用。
我的问题:
是否可以在SpannableString中的Clickable对象周围放置边框?因此,基本上每个Clickable对象/字符串都必须具有自己的边框。
我认为也许updateDrawState方法可能能够提供帮助,但没有。有人知道如何实现吗?
谢谢。
最佳答案
我扩展了ReplacementSpan
以勾勒出轮廓。不幸的是I can't manage to make them wrap,但是如果您只是想将轮廓应用于几个单词,它应该可以正常工作。要使其可点击,您只需在设置该子类之前使用您提到的setSpan(ClickableSpanWithoutUnderline...)
的子类。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_replacement_span);
final Context context = this;
final TextView tv = (TextView) findViewById(R.id.tv);
Spannable span = Spannable.Factory.getInstance().newSpannable("Some string");
span.setSpan(new BorderedSpan(context), 0, span.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(span, TextView.BufferType.SPANNABLE);
}
public static class BorderedSpan extends ReplacementSpan {
final Paint mPaintBorder, mPaintBackground;
int mWidth;
Resources r;
int mTextColor;
public BorderedSpan(Context context) {
mPaintBorder = new Paint();
mPaintBorder.setStyle(Paint.Style.STROKE);
mPaintBorder.setAntiAlias(true);
mPaintBackground = new Paint();
mPaintBackground.setStyle(Paint.Style.FILL);
mPaintBackground.setAntiAlias(true);
r = context.getResources();
mPaintBorder.setColor(Color.RED);
mPaintBackground.setColor(Color.GREEN);
mTextColor = Color.BLACK;
}
@Override
public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
//return text with relative to the Paint
mWidth = (int) paint.measureText(text, start, end);
return mWidth;
}
@Override
public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
canvas.drawRect(x, top, x + mWidth, bottom, mPaintBackground);
canvas.drawRect(x, top, x + mWidth, bottom, mPaintBorder);
paint.setColor(mTextColor); //use the default text paint to preserve font size/style
canvas.drawText(text, start, end, x, y, paint);
}
}
关于android - SpannableString中Clickable对象的边框,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16026577/