1. 程式人生 > >部分字型高亮並且可點選,ClickableSpan

部分字型高亮並且可點選,ClickableSpan

首先,得寫一個類繼承ClickableSpan

private class ClickableSpanNoUnderLine extends ClickableSpan {

        private static final int DEFAULT_COLOR = -1111;
        private int color = DEFAULT_COLOR;

        @Override
        public void onClick(View widget) {
            Log.d(TAG, "onClick");
            Context ctx = widget.getContext();

            Intent intent = new Intent("xxxx");
            try {
                ctx.startActivity(intent);
            } catch (ActivityNotFoundException e) {
                Log.w("",
                        "Actvity was not found for intent, " + intent.toString());
            }
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            // 設定文字顏色
            if (this.color == DEFAULT_COLOR) {
                ds.setColor(ds.linkColor);
            } else {
                ds.setColor(this.color);
            }
            ds.clearShadowLayer();
            // 去除下劃線
            ds.setUnderlineText(false);
            ds.bgColor = Color.TRANSPARENT;
        }
    }

第二步,使用

String tcContent = getString(R.string.tc_content);
String seeMore = getString(R.string.see_more);
String content = tcContent + seeMore;
        
SpannableStringBuilder ssb = new SpannableStringBuilder(content);
ClickableSpanNoUnderLine span = new ClickableSpanNoUnderLine();
ssb.setSpan(span, tcContent.length(), content.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        
mTcContent = (TextView)findViewById(R.id.id_tc_content);
mTcContent.setText(ssb);
// 在單擊時凡是有要執行的動作,都必須設定MovementMethod物件
mTcContent.setMovementMethod(LinkMovementMethod.getInstance());
// 設定點選後的顏色,這裡涉及到ClickableSpan的點選背景
mTcContent.setHighlightColor(0x00000000);