1. 程式人生 > >Android TextView ClickableSpan 分段點選實現

Android TextView ClickableSpan 分段點選實現

最新專案遇到TextView分段點選的問題,類似新浪微博@多個人的點選效果,效果圖如下:
這裡寫圖片描述

這裡寫圖片描述

具體主要通過CustomClickableSpan類來實現,CustomClickableSpan繼承自ClickableSpan,在構造方法傳入子串的開始位置。

Activity類:
public class ClickableSpanActivity extends AppCompatActivity {

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_clickable_span);

    TextView tvContent = (TextView) findViewById(R.id.TextView_Content);

    String content = "@阿里巴巴 @百度 @騰訊 真有錢!";

    layoutContent(tvContent, content);
}

private void layoutContent(TextView textView, String content) {
    if (!content.contains("@")) {
        textView.setText(content);
        return;
    }

    SpannableStringBuilder builder = new SpannableStringBuilder(content);

    int index = 0;
    while (content.indexOf("@", index) != -1) {
        int atIndex = content.indexOf("@", index);  //@的位置
        int sIndex = content.indexOf(" ", atIndex); //空格的位置

        index = sIndex;
        if (sIndex < atIndex) { //格式不符合
            continue;
        }
        Log.d("ClickSpan", "@ = " + atIndex + " S = " + sIndex);

        CustomClickableSpan clickableSpan = new CustomClickableSpan(this, atIndex);
        builder.setSpan(clickableSpan, atIndex, sIndex, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    }

    textView.setMovementMethod(LinkMovementMethod.getInstance());
    textView.setText(builder);
}

}

CustomClickableSpan類:
public class CustomClickableSpan extends ClickableSpan {

private Context mContext;
private int mAtIndex;

public CustomClickableSpan(Context context, int atIndex) {
    mContext = context;
    mAtIndex = atIndex;
}

@Override
public void onClick(View widget) {
    if (widget instanceof TextView) {
        TextView textView = (TextView) widget;
        Log.d("SpanContent", "Content = " + textView.getText().toString());

        String str = textView.getText().toString();
        int sIndex = str.indexOf(" ", mAtIndex);
        Toast.makeText(mContext, str.substring(mAtIndex + 1, sIndex), Toast.LENGTH_SHORT).show();
    }
}

@Override
public void updateDrawState(TextPaint ds) {
    super.updateDrawState(ds);
    ds.setColor(Color.BLUE);
    ds.setUnderlineText(false);
    ds.clearShadowLayer();
}

}