2013-04-15 60 views
3

目前我有一個SpannableString對象,其中設置了多個可點擊對象。所以一個字符串有許多可點擊的對象,並且取決於用戶點擊哪個單詞/部分,應用程序將繼續並執行該點擊事件的處理。有一天,我在這裏問了關於擺脫SpannableString中部分單詞的藍色下劃線的stackoverflow,答案是ClickableSpan類的子類,並覆蓋updateDrawState方法並將underlineText設置爲false,以使其工作。SpannableString中可點擊對象的邊框

我的問題: 是否可以在SpannableString中的Clickable對象周圍放置邊框?所以基本上每個Clickable對象/字符串必須有自己的邊框。

我想也許updateDrawState方法可能能夠幫助,但它沒有。有人知道這可以實現嗎?

謝謝。

+0

看看BackgroundColorSpan是怎麼做的 - 邊界實際上只是一個空心的背景。 – CommonsWare

+0

@CommonsWare我剛剛嘗試過BackgroundColorSpan,但它將背景設置爲紅色,而不是像我之後創建紅色邊框一樣? – Ash

+0

@CommonsWare有沒有使用/調整BackgroundColorSpan的特殊方式,以便它可以顯示紅色邊框/輪廓? – Ash

回答

0

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