【问题标题】:Border in Clickable object in SpannableStringSpannableString 中可点击对象的边框
【发布时间】:2015-04-01 00:24:38
【问题描述】:

目前我有一个 SpannableString 对象,其中设置了多个 Clickable 对象。因此,一个字符串有许多 Clickable 对象,根据用户单击的单词/部分,应用程序将继续处理该单击事件。前几天我在 stackoverflow 上问过关于摆脱 SpannableString 中部分单词的蓝色下划线的问题,答案是对 ClickableSpan 类进行子类化,并覆盖 updateDrawState 方法并将 underlineText 设置为 false,这很有效。

我的问题: 是否可以在 SpannableString 中的 Clickable 对象周围放置边框?所以基本上每个 Clickable 对象/字符串都必须有自己的边框。

我认为 updateDrawState 方法可能会有所帮助,但它没有。有人知道如何实现吗?

谢谢。

【问题讨论】:

  • 看看BackgroundColorSpan 是如何工作的——边框实际上只是一个空心背景。
  • @CommonsWare 我刚刚尝试了 BackgroundColorSpan,但它将背景设置为红色,而不是像我之后那样创建红色边框?
  • @CommonsWare 是否有一种特殊的方式来使用/调整 BackgroundColorSpan 以便它可以显示红色边框/轮廓?
  • 我的意思是让你看看BackgroundColorSpan实现,了解如何编写你自己的 i> OutlinedClickableSpan 或类似的。

标签: android


【解决方案1】:

我扩展了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);
    }
}

【讨论】:

  • 不支持多行文字
  • @user924 如果您需要多行,请随时在答案中投票和/或赏金我的链接问题
猜你喜欢
  • 1970-01-01
  • 2010-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-19
  • 2014-01-08
  • 2015-06-10
相关资源
最近更新 更多