安卓Html标签,创意工具类

之前开发项目中,遇到了在Textview中使用Html标签的情形,由于在代码中使用字符串,Android Studio上一堆的黄色警告,而且对于过时的Html.fromHtml,拿它一点办法也没有。

对于有代码强迫症的我来说,心里各种纠结,各种不爽,于是脑洞大开,设计了下面这个工具类,方便使用Html中的各个标签。

使用场景:

EasyHtml2 easyHtml = new EasyHtml2();
textView.setText(easyHtml
                        .appendBr2("标题:")
                        .appendBr("1.第一点;")
                        .appendBr("2.第二点;")
                        .build());

源码:

/**
 * 脑洞大开的工具包
 * Created by ChenSS on 2016/11/7.
 */
public class EasyHtml2 {
    private StringBuilder sBuilder;

    public EasyHtml2() {
        sBuilder = new StringBuilder(120);
    }

    /**
     * 添加一个普通的字符串
     *
     * @param source
     */
    public EasyHtml2 append(String source) {
        sBuilder.append(source);
        return this;
    }

    /**
     * 段落标签
     */
    public EasyHtml2 appendP(String source) {
        sBuilder.append("<p>");
        sBuilder.append(source);
        sBuilder.append("</p>");
        return this;
    }

    /**
     * 结尾追加两个换行
     */
    public EasyHtml2 appendBr2(String source) {
        sBuilder.append(source);
        sBuilder.append("<br><br>");
        return this;
    }

    /**
     * 结尾追加换行
     */
    public EasyHtml2 appendBr(String source) {
        sBuilder.append(source);
        sBuilder.append("<br>");
        return this;
    }

    /**
     * font标签,可以指定颜色
     *
     * @param color 格式为"#0000FF"
     */
    public EasyHtml2 appendFont(String source, String color) {
        sBuilder.append("<font color='").append(color).append("'>");
        sBuilder.append(source);
        sBuilder.append("</font>");
        return this;
    }

    /**
     * 大字号
     */
    public EasyHtml2 appendBig(String source, String color) {
        sBuilder.append("<big>");
        sBuilder.append(source);
        sBuilder.append("</big>");
        return this;
    }

    /**
     * 小字号
     */
    public EasyHtml2 appendSmall(String source, String color) {
        sBuilder.append("<small>");
        sBuilder.append(source);
        sBuilder.append("</small>");
        return this;
    }

    /**
     * 超链接标签,要使链接生效,请设置android:autoLink
     */
    public EasyHtml2 appendA(String source, String url) {
        sBuilder.append("<a href='").append(url).append("'>");
        sBuilder.append(source);
        sBuilder.append("</a>");
        return this;
    }

    /**
     * 带下划线标签
     */
    public EasyHtml2 appendU(String source, String url) {
        sBuilder.append("<u>");
        sBuilder.append(source);
        sBuilder.append("</u>");
        return this;
    }

    public Spanned build() {
        //使用过时的fromHtml,最新的API版本要求过高
        return Html.fromHtml(sBuilder.toString());
    }
}

posted on 2016-11-16 14:10  疯狂的妞妞  阅读(173)  评论(0编辑  收藏  举报

导航