近期在做评论的时候须要实现这样的效果
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvamF2X2ltYmE=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">网上百度了一下,就是自己定义一个类继承4ClickableSpan,然后在updateDrawState方法中设置是否下划线为false,可是看了一下网上实现的方法是直接在新类的OnClick方法中实现onClick操作,感觉不太easy扩展使用,于是我自己定义了一个接口,通过接口实现了外部代码调用。详细代码例如以下:
public class NoLineClickableSpan extends ClickableSpan{ private IOnNoLineTextClick iOnNoLineTextClick; public NoLineClickableSpan() {
super();
} @Override
public void updateDrawState(TextPaint ds) {
ds.setColor(ds.linkColor);
ds.setUnderlineText(false);
} @Override
public void onClick(View widget) {
iOnNoLineTextClick.onClick();
} public void setOnNoLineTextClick(IOnNoLineTextClick i){
iOnNoLineTextClick = i;
}
public interface IOnNoLineTextClick{
public void onClick();
}
}
XML文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" > <TextView
android:id="@+id/tv_test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="小西回复大东方:你是个大大大的好好人" /> </RelativeLayout>
MainActivity调用代码例如以下:
public class MainActivity extends Activity {
private TextView tv_test;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
} private void initView() {
tv_test = (TextView) findViewById(R.id.tv_test);
tv_test.setMovementMethod(LinkMovementMethod.getInstance());
SpannableString spanString = new SpannableString(tv_test.getText().toString()); NoLineClickableSpan span = new NoLineClickableSpan();
span.setOnNoLineTextClick(new IOnNoLineTextClick() { @Override
public void onClick() {
System.out.println("点击用户");
}
}); spanString.setSpan(span, 0, 2, SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
tv_test.setText(spanString);
}
}
当中spanString.setSpan(span,0,2,SpannableString.SPAN_EXCLUSIVE_EXCLUSIZE); 0,2 分别代表超链接字体的開始位置和结束位置,我这里取2,当点击小西时执行结果例如以下:
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvamF2X2ltYmE=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">