TextView加载Html无法显示字体大小

如题,我在实际工作中遇到的情况,查阅相关资料,安卓的setText(Html.fromHtml(source))不支持font、span中的size,用style样式也不行。

直接上代码,自定义一个TagHandler ,继承Html.TagHandler

public class HtmlSizeTag implements Html.TagHandler {
    private String tagName;
    // 存放标签所有属性键值对
    final HashMap attributes = new HashMap<>();

    private int startIndex = 0;
    private int endIndex = 0;
    public HtmlSizeTag(String tagName) {
        this.tagName = tagName;
    }

    @Override
    public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
        if(tag.toLowerCase().equals(tagName)) {
            // 解析所有属性值
            parseAttributes(xmlReader);
            if(opening){
                startIndex = output.length();
            }else{
                endEndHandleTag(output,xmlReader);
            }
        }
    }

    public void endEndHandleTag( Editable output, XMLReader xmlReader) {
        endIndex = output.length();
        // 获取对应的属性值
        String color = attributes.get("color");
        String size = attributes.get("size");
        size = size.split("px")[0];

        // 设置颜色
        if (!TextUtils.isEmpty(color)) {
            output.setSpan(new ForegroundColorSpan(Color.parseColor(color)), startIndex, endIndex,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        // 设置字体大小
        if (!TextUtils.isEmpty(size)) {
            output.setSpan(new AbsoluteSizeSpan(Integer.parseInt(size)), startIndex, endIndex,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }



    private void parseAttributes(final XMLReader xmlReader) {
        try {
            Field elementField = xmlReader.getClass().getDeclaredField("theNewElement");
            elementField.setAccessible(true);
            Object element = elementField.get(xmlReader);
            Field attsField = element.getClass().getDeclaredField("theAtts");
            attsField.setAccessible(true);
            Object atts = attsField.get(element);
            Field dataField = atts.getClass().getDeclaredField("data");
            dataField.setAccessible(true);
            String[] data = (String[]) dataField.get(atts);
            Field lengthField = atts.getClass().getDeclaredField("length");
            lengthField.setAccessible(true);
            int len = (Integer) lengthField.get(atts);
            for (int i = 0; i < len; i++) {
                attributes.put(data[i * 5 + 1], data[i * 5 + 4]);
            }
        } catch (Exception e) {

        }
    }

}

使用

String html="" + txt + "";
 textview.setText(Html.fromHtml(html, null, new HtmlSizeTag("myfont")));

更多资料:
点击 https://www.jianshu.com/p/4bb31a128e73
点击https://blog.csdn.net/u013626215/article/details/77720232

你可能感兴趣的:(TextView加载Html无法显示字体大小)