android textview html font标签不好用

textview可以显示html标签的效果,但是最基本的字体大小,颜色font标签却不好用,根本无法使用设置字体大小,看了下源码原来是个bug,在设置font属性的时候就没有设置字体大小,考虑html还提供自定标签的功能,思路是替换font标签自己解析设置。

用到的接口是Html类TagHandler接口

public class DdbFontHandler implements TagHandler {

	private int startIndex = 0;
	private int stopIndex = 0;

	@Override
	public void handleTag(boolean opening, String tag, Editable output,
			XMLReader xmlReader) {
		processAttributes(xmlReader);
		
		if(tag.equalsIgnoreCase("ddbfont")){
			if(opening){
				startFont(tag, output, xmlReader);
			}else{
				endFont(tag, output, xmlReader);
			}
		}

	}
	
    public void startFont(String tag, Editable output, XMLReader xmlReader) {  
        startIndex = output.length();  
    }  
  
    public void endFont(String tag, Editable output, XMLReader xmlReader){  
        stopIndex = output.length();  
        
        String color = attributes.get("color");
        String size = attributes.get("size");
        size = size.split("px")[0];
        if(!TextUtils.isEmpty(color) && !TextUtils.isEmpty(size)){
	        output.setSpan(new ForegroundColorSpan(Color.parseColor(color)), startIndex, stopIndex,  Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  
	        output.setSpan(new AbsoluteSizeSpan(Utils.dipToPx(GApp.instance(), Integer.parseInt(size))), startIndex, stopIndex,  Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  
        }else{
        	output.setSpan(new ForegroundColorSpan(0xff2b2b2b), startIndex, stopIndex,  Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  
        }
    } 
    
    final HashMap<String, String> attributes = new HashMap<String, String>();

    private void processAttributes(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);

            /**
             * MSH: Look for supported attributes and add to hash map.
             * This is as tight as things can get :)
             * The data index is "just" where the keys and values are stored. 
             */
            for(int i = 0; i < len; i++)
                attributes.put(data[i * 5 + 1], data[i * 5 + 4]);
        }
        catch (Exception e) {
        }
    }

}
这个比较通用,自定义其他标签。网上还有针对这个问题其他思路,也是不错的

http://blog.csdn.net/u010418593/article/details/9322197

你可能感兴趣的:(html,android,标签)