给你的TextView中的部分文字加入没有下划线的超链接

来源:互联网 发布:mac os双系统安装教程 编辑:程序博客网 时间:2024/06/06 01:35

项目优化,当网络请求失败时加上提醒,并可以点击TextView中的“刷新”两个字再次请求。使用ClickableSpan对超链接进行设置。默认情况下的样式是这样的:


想要的样式是这样的:


我们使用默认ClickableSpan的方法如下:

SpannableStringBuilder builder = new SpannableStringBuilder("(╯╰)\n网络走丢了,请刷新试试");int i = "(╯╰)\n网络走丢了,请刷新试试".indexOf("");builder.setSpan(new ClickableSpan() {    @Override    public void onClick(View widget) {        page = 0;        httpGetList(HTTP_GETDETAILDATA);    }},i,i+2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);noData_detailData.setText(builder);noData_detailData.setMovementMethod(LinkMovementMethod.getInstance());Utils.setToast(context, "网络偷了会儿懒,请稍后重试");

这些代码中最需要强调的就是

noData_detailData.setMovementMethod(LinkMovementMethod.getInstance());

这一行是必须的,不然能够显示样式,但是没法实现点击效果。


很明显默认的样式无法满足我们的需要了,现在实现自定义的样式:

自定义NoUnderLineClickableSpan继承自ClickableSpan,来看一下ClickableSpan的源码:

/** * If an object of this type is attached to the text of a TextView * with a movement method of LinkMovementMethod, the affected spans of * text can be selected.  If clicked, the {@link #onClick} method will * be called. */public abstract class ClickableSpan extends CharacterStyle implements UpdateAppearance {    /**     * Performs the click action associated with this span.     */    public abstract void onClick(View widget);       /**     * Makes the text underlined and in the link color.     */    @Override    public void updateDrawState(TextPaint ds) {        ds.setColor(ds.linkColor);        ds.setUnderlineText(true);    }}

这个类中只有两个方法,onClick方法是我们需要实现的方法,很明显是我们点击文字后要干的事,我这里就是通过http请求数据。

第二个方法是我们自定义的重点,也很简单嘛,只有两行,ds.setColor肯定是在设置超链接文字的颜色,也就是项目中“刷新”这两个字的颜色。ds.setUnderlineText,看名字也知道是在设置下划线,传入boolean值,当传入true时超链接文字将会显示下划线,当传入false时超链接文字将不会显示下划线,就是这么简单。


下面是项目中自定义的NoUnderlineClickableSpan的代码:

/** * 自定义没有下划线,文字是蓝色的ClickableSpan * Created by Qiju on 2017/10/16. * */public class NoUnderLineClickableSpan extends ClickableSpan {    @Override    public void onClick(View widget) {    }    /**     * 设置超链接颜色为蓝色,没有下划线     * @param ds     */    @Override    public void updateDrawState(TextPaint ds) {        ds.setColor(Color.BLUE);        ds.setUnderlineText(false);    }}







阅读全文
0 0