Android - TextView - Span 設定及SpanClick處理

Android - TextView - Span 設定及SpanClick處理

	/**
	 * 標籤設定
	 */
	public void setLoginSpan() {
		SpannableString msp = null;

		String desc = "你是否要 登入 ?";
		String login_text = "登入";
		int login_start = desc.indexOf(login_text);
		int login_end = login_start + login_text.length();

		msp = new SpannableString(desc);
		msp.setSpan(new ForegroundColorSpan(Color.BLUE), login_start, login_end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		msp.setSpan(new UnderlineSpan(), login_start, login_end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		msp.setSpan(mLoginSpanClick, login_start, login_end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

		txtv_desc.setText(msp);
		txtv_desc.setMovementMethod(LinkMovementMethod.getInstance());
	}

	public ClickableSpan mLoginSpanClick = new ClickableSpan() {
		@Override
		public void onClick(View widget) {
			//TODO:Login
		}
	};

後來我做了一個共用元件 
以後要設定可按動作就沒這麼困難

public class SpanStringBuilder {
    private String mText = "";
    SpannableString msp;
    public SpanStringBuilder(String text){
        mText = text;
        msp = new SpannableString(mText);
    }

    public void addSpan(String text,ClickableSpan spanClick) {
        int start, end;
        start = mText.indexOf(text);
        end = start + text.length();

        msp.setSpan(new ForegroundColorSpan(Color.BLUE), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        msp.setSpan(new UnderlineSpan(), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        msp.setSpan(spanClick, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    public SpannableString getSpannableString() {
        return msp;
    }
}

以後這樣使用就可以了


		SpanStringBuilder builder = new SpanStringBuilder("你是否要 登入 ?");
		builder.addSpan("登入",mLoginSpanClick);

		txtv_desc.setText(builder.getSpannableString());
		txtv_desc.setMovementMethod(LinkMovementMethod.getInstance());