您的位置:首页 > 移动开发 > Android开发

Android TextView ClickableSpan 分段点击实现

2016-10-19 12:02 453 查看
最新项目遇到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();
}


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐