Html.fromHtml()中Html.TagHandler()的使用

,前几天跑到这么个问题,要求显示这样的文字 1500/天 原价:20000元,而且文字的样式由服务器控制,所以我就自然的想到了Html.fromHtml()这个方法,它是用来解析Html的。好!我就用它来解析一下上面的文字的Html,先把上面文字的html贴出看看:<font style="color:#ff6c00;font-size:18px"> 1500/天</font>&nbsp;<font style="TEXT-DECORATION: line-through;color:#808080;font-size:10px">原价:20000元 </font>,就是这样的一段html。

好了上代码:

布局文件(其实就是一个TextView控件):

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/testHtml"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

java代码:

  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView textView = (TextView) findViewById(R.id.testHtml);

        String htmlStr = "<font style=\"color:#ff6c00;font-size:18px\"> 1500/天</font> <font style=\"TEXT-DECORATION: line-through;" +
                "color:#808080;font-size:10px\">原价:20000元 </font>";

        textView.setText(Html.fromHtml(htmlStr));
    }
运行结果:


额!完全没有样式显示出来,就简简单单的把文字内容显示出来了。Html确定是没有写错的。那么是为什么呢?

Html.fromHtml(),呃!机智的我知道了,他是Html.fromHtml()不是Html.fromCss(),应该是不支持样式的。好!那我改改,改成全部用Html标签表示。 1500/天 原价:20000元,这个就是用html标签表示的。代码:<font color='#ff6c00' size='4'> 1500/天</font>&nbsp;<del><font  color='#808080' size='2'>原价:20000元 </font></del>,好!那我来试试。

java代码:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView textView = (TextView) findViewById(R.id.testHtml);

        String htmlStr = "<font style=\"color:#ff6c00;font-size:18px\"> 1500/天</font> <font style=\"TEXT-DECORATION: line-through;" +
                "color:#808080;font-size:10px\">原价:20000元 </font>";

        String htmlStr_1 = "<font color='#ff6c00' size='4'> 1500/天</font> <del><font  color='#808080' size='2'>原价:20000元 </font></del>";

        textView.setText(Html.fromHtml(htmlStr_1));
    }
运行结果:


font标签的color属性表现出来,但是del标签和font标签的size属性没有表现出来。难道Html.fromHtml()不支持del标签?那我用strike试试!html代码改为:<font color='#ff6c00' size='4'> 1500/天</font>&nbsp;<strike><font  color='#808080' size='2'>原价:20000元 </font></strike>这样。

java代码:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView textView = (TextView) findViewById(R.id.testHtml);

        String htmlStr = "<font style=\"color:#ff6c00;font-size:18px\"> 1500/天</font> <font style=\"TEXT-DECORATION: line-through;" +
                "color:#808080;font-size:10px\">原价:20000元 </font>";

        String htmlStr_1 = "<font color='#ff6c00' size='4'> 1500/天</font> <del><font  color='#808080' size='2'>原价:20000元 </font></del>";

        String htmlStr_2 = "<font color='#ff6c00' size='4'> 1500/天</font> <strike><font  color='#808080' size='2'>原价:20000元 </font></strike>";

        textView.setText(Html.fromHtml(htmlStr_2));
    }
运行结果:

额!貌似strike也不支持。那Html.fromHtml()这个到底支持什么啊。

来来~我们看看它的庐山真面目,找到这个类:android.text.Html

看看它的这个方法:

 private void handleStartTag(String tag, Attributes attributes) {
        if (tag.equalsIgnoreCase("br")) {
            // We don't need to handle this. TagSoup will ensure that there's a </br> for each <br>
            // so we can safely emite the linebreaks when we handle the close tag.
        } else if (tag.equalsIgnoreCase("p")) {
            handleP(mSpannableStringBuilder);
        } else if (tag.equalsIgnoreCase("div")) {
            handleP(mSpannableStringBuilder);
        } else if (tag.equalsIgnoreCase("strong")) {
            start(mSpannableStringBuilder, new Bold());
        } else if (tag.equalsIgnoreCase("b")) {
            start(mSpannableStringBuilder, new Bold());
        } else if (tag.equalsIgnoreCase("em")) {
            start(mSpannableStringBuilder, new Italic());
        } else if (tag.equalsIgnoreCase("cite")) {
            start(mSpannableStringBuilder, new Italic());
        } else if (tag.equalsIgnoreCase("dfn")) {
            start(mSpannableStringBuilder, new Italic());
        } else if (tag.equalsIgnoreCase("i")) {
            start(mSpannableStringBuilder, new Italic());
        } else if (tag.equalsIgnoreCase("big")) {
            start(mSpannableStringBuilder, new Big());
        } else if (tag.equalsIgnoreCase("small")) {
            start(mSpannableStringBuilder, new Small());
        } else if (tag.equalsIgnoreCase("font")) {
            startFont(mSpannableStringBuilder, attributes);
        } else if (tag.equalsIgnoreCase("blockquote")) {
            handleP(mSpannableStringBuilder);
            start(mSpannableStringBuilder, new Blockquote());
        } else if (tag.equalsIgnoreCase("tt")) {
            start(mSpannableStringBuilder, new Monospace());
        } else if (tag.equalsIgnoreCase("a")) {
            startA(mSpannableStringBuilder, attributes);
        } else if (tag.equalsIgnoreCase("u")) {
            start(mSpannableStringBuilder, new Underline());
        } else if (tag.equalsIgnoreCase("sup")) {
            start(mSpannableStringBuilder, new Super());
        } else if (tag.equalsIgnoreCase("sub")) {
            start(mSpannableStringBuilder, new Sub());
        } else if (tag.length() == 2 &&
                   Character.toLowerCase(tag.charAt(0)) == 'h' &&
                   tag.charAt(1) >= '1' && tag.charAt(1) <= '6') {
            handleP(mSpannableStringBuilder);
            start(mSpannableStringBuilder, new Header(tag.charAt(1) - '1'));
        } else if (tag.equalsIgnoreCase("img")) {
            startImg(mSpannableStringBuilder, attributes, mImageGetter);
        } else if (mTagHandler != null) {
            mTagHandler.handleTag(true, tag, mSpannableStringBuilder, mReader);
        }
    }
一切突然明朗了吧!

它支持:

br换行符 
p定义段落 
div定义文档中的分区或节 
strong用于强调文本用于强调文本
b粗体文本粗体文本
em斜体显示斜体显示
cite斜体显示斜体显示
dfn斜体显示斜体显示
i斜体显示斜体显示
big大号字体大号字体
small小号字体小号字体
font字体标签字体标签
blockquote标签定义块引用
标签定义块引用
tt字体显示为等宽字体字体显示为等宽字体
a超链接百度
u下划线下划线
sup上标我有上标上标
sub下标我有下标下标
h1-h6标题字体

这是标题 1

这是标题 2

这是标题 3

这是标题 4
这是标题 5
这是标题 6
img图片少司命
还有一个问题,它既然支持font标签,为什么size属性无效呢?字体不能控制大小,这是不是有点蹩脚啊!来~看看这个方法:

private static void startFont(SpannableStringBuilder text,
                                  Attributes attributes) {
        String color = attributes.getValue("", "color");
        String face = attributes.getValue("", "face");

        int len = text.length();
        text.setSpan(new Font(color, face), len, len, Spannable.SPAN_MARK_MARK);
    }
font只支持color和face2个属性。所以你设置size是无效的。

那我的 1500/天 原价:20000元这个效果就不能做到吗?也不是,其实要解决的问题也就只有2个,一个就是让Html.fromHtml()可以认识<del>标签,另一个就是让font支持size属性,这就要用到Html.TagHandler()了。

我们首先解决第一个问题:让Html.fromHtml()可以认识<del>标签。

java代码:

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView textView = (TextView) findViewById(R.id.testHtml);

        String htmlStr = "<font style=\"color:#ff6c00;font-size:18px\"> 1500/天</font> <font style=\"TEXT-DECORATION: line-through;" +
                "color:#808080;font-size:10px\">原价:20000元 </font>";

        String htmlStr_1 = "<font color='#ff6c00' size='4'> 1500/天</font> <del><font  color='#808080' size='2'>原价:20000元 </font></del>";

        String htmlStr_2 = "<font color='#ff6c00' size='4'> 1500/天</font> <strike><font  color='#808080' size='2'>原价:20000元 </font></strike>";

        textView.setText(Html.fromHtml(htmlStr_1,null, new Html.TagHandler() {
            int startTag;
            int endTag;
            @Override
            public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
                if (tag.equalsIgnoreCase("del")){
                    if(opening){
                        startTag = output.length();
                    }else{
                        endTag = output.length();
                        output.setSpan(new StrikethroughSpan(),startTag,endTag, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    }
                }
            }
        }));
    }
handleTag()方法三个参数opening是否是标签的开始,tag标签的名字,output输出的文字,xmlReader用来获取自定义属性。

用tag来识别标签,然后用SpannableString对文字进行样式。

SpannableString功能有以下:

1、BackgroundColorSpan 背景色 
2、ClickableSpan 文本可点击,有点击事件
3、ForegroundColorSpan 文本颜色(前景色)
4、MaskFilterSpan 修饰效果,如模糊(BlurMaskFilter)、浮雕(EmbossMaskFilter)
5、MetricAffectingSpan 父类,一般不用
6、RasterizerSpan 光栅效果
7、StrikethroughSpan 删除线(中划线)
8、SuggestionSpan 相当于占位符
9、UnderlineSpan 下划线
10、AbsoluteSizeSpan 绝对大小(文本字体)
11、DynamicDrawableSpan 设置图片,基于文本基线或底部对齐。
12、ImageSpan 图片
13、RelativeSizeSpan 相对大小(文本字体)
14、ReplacementSpan 父类,一般不用
15、ScaleXSpan 基于x轴缩放
16、StyleSpan 字体样式:粗体、斜体等
17、SubscriptSpan 下标(数学公式会用到)
18、SuperscriptSpan 上标(数学公式会用到)
19、TextAppearanceSpan 文本外貌(包括字体、大小、样式和颜色)
20、TypefaceSpan 文本字体
21、URLSpan 文本超链接

好了我们看看识别之后的效果:


中划线种出来了。

再解决第二个问题:

java代码:

/**
 * 自定义的一html标签解析
 * <p>
 * Created by Siy on 2016/11/19.
 */

public class CustomerTagHandler implements Html.TagHandler {

    /**
     * html 标签的开始下标
     */
    private Stack<Integer> startIndex;

    /**
     * html的标签的属性值 value,如:<size value='16'></size>
     * 注:value的值不能带有单位,默认就是sp
     */
    private Stack<String> propertyValue;

    @Override
    public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
        Log.e("TAG","handleTag:"+tag);
        if (opening) {
            handlerStartTAG(tag, output, xmlReader);
        } else {
            handlerEndTAG(tag, output);
        }
    }

    /**
     * 处理开始的标签位
     *
     * @param tag
     * @param output
     * @param xmlReader
     */
    private void handlerStartTAG(String tag, Editable output, XMLReader xmlReader) {
        if (tag.equalsIgnoreCase("del")) {
            handlerStartDEL(output);
        } else if (tag.equalsIgnoreCase("font")) {
            handlerStartSIZE(output, xmlReader);
        }
    }

    /**
     * 处理结尾的标签位
     *
     * @param tag
     * @param output
     */
    private void handlerEndTAG(String tag, Editable output) {
        if (tag.equalsIgnoreCase("del")) {
            handlerEndDEL(output);
        } else if (tag.equalsIgnoreCase("font")) {
            handlerEndSIZE(output);
        }
    }

    private void handlerStartDEL(Editable output) {
        if (startIndex == null) {
            startIndex = new Stack<>();
        }
        startIndex.push(output.length());
    }

    private void handlerEndDEL(Editable output) {
        output.setSpan(new StrikethroughSpan(), startIndex.pop(), output.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    private void handlerStartSIZE(Editable output, XMLReader xmlReader) {
        if (startIndex == null) {
            startIndex = new Stack<>();
        }
        startIndex.push(output.length());

        if (propertyValue == null) {
            propertyValue = new Stack<>();
        }

        propertyValue.push(getProperty(xmlReader, "size"));
    }

    private void handlerEndSIZE(Editable output) {

        if (!isEmpty(propertyValue)) {
            try {
                int value = Integer.parseInt(propertyValue.pop());
                output.setSpan(new AbsoluteSizeSpan(sp2px(MainApplication.getInstance(), value)), startIndex.pop(), output.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 利用反射获取html标签的属性值
     *
     * @param xmlReader
     * @param property
     * @return
     */
    private String getProperty(XMLReader xmlReader, String property) {
        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++) {
                // 这边的property换成你自己的属性名就可以了
                if (property.equals(data[i * 5 + 1])) {
                    return data[i * 5 + 4];
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 集合是否为空
     *
     * @param collection
     * @return
     */
    public static boolean isEmpty(Collection collection) {
        return collection == null || collection.isEmpty();
    }

    /**
     * 缩放独立像素 转换成 像素
     * @param context
     * @param spValue
     * @return
     */
    public static int sp2px(Context context, float spValue){
        return (int)(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,spValue,context.getResources().getDisplayMetrics())+0.5f);
    }
}

getProperty()方法是用来获取标签的属性值。

这里还是有一个问题,直接看运行结果:


font 还是没有处理字体大小。为什么了?看回前面的handleStartTag方法,用的是if...else if语法,而且对mTagHandler!=null的判断是放在最后的,只要前面有一个标签成功就不会执行这里,所以对Html.formHtml()支持的标签加属性支持是行不通的。既然对支持的标签加属性行不通,那我们自己增加一size 标签给他value属性标识size的大小不就行了。

java代码:

这里我们要改一下html代码,注意htmlStr_3:

  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView textView = (TextView) findViewById(R.id.testHtml);

        String htmlStr = "<font style=\"color:#ff6c00;font-size:18px\"> 1500/天</font> <font style=\"TEXT-DECORATION: line-through;" +
                "color:#808080;font-size:10px\">原价:20000元 </font>";

        String htmlStr_1 = "<font color='#ff6c00' size='16'> 1500/天</font> <del><font  color='#808080' size='12'>原价:20000元 </font></del>";

        String htmlStr_2 = "<font color='#ff6c00' size='4'> 1500/天</font> <strike><font  color='#808080' size='2'>原价:20000元 </font></strike>";

        String htmlStr_3 = "<font color='#ff6c00'> <size value='20'>1500/天</size></font> <del><font  color='#808080'><size value='12'>原价:20000元</size> </font></del>";

        textView.setText(Html.fromHtml(htmlStr_3,null, new CustomerTagHandler()));
    }
/**
 * 自定义的一html标签解析
 * <p>
 * Created by Siy on 2016/11/19.
 */

public class CustomerTagHandler implements Html.TagHandler {

    /**
     * html 标签的开始下标
     */
    private Stack<Integer> startIndex;

    /**
     * html的标签的属性值 value,如:<size value='16'></size>
     * 注:value的值不能带有单位,默认就是sp
     */
    private Stack<String> propertyValue;

    @Override
    public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
        Log.e("TAG","handleTag:"+tag);
        if (opening) {
            handlerStartTAG(tag, output, xmlReader);
        } else {
            handlerEndTAG(tag, output);
        }
    }

    /**
     * 处理开始的标签位
     *
     * @param tag
     * @param output
     * @param xmlReader
     */
    private void handlerStartTAG(String tag, Editable output, XMLReader xmlReader) {
        if (tag.equalsIgnoreCase("del")) {
            handlerStartDEL(output);
        } else if (tag.equalsIgnoreCase("size")) {
            handlerStartSIZE(output, xmlReader);
        }
    }

    /**
     * 处理结尾的标签位
     *
     * @param tag
     * @param output
     */
    private void handlerEndTAG(String tag, Editable output) {
        if (tag.equalsIgnoreCase("del")) {
            handlerEndDEL(output);
        } else if (tag.equalsIgnoreCase("size")) {
            handlerEndSIZE(output);
        }
    }

    private void handlerStartDEL(Editable output) {
        if (startIndex == null) {
            startIndex = new Stack<>();
        }
        startIndex.push(output.length());
    }

    private void handlerEndDEL(Editable output) {
        output.setSpan(new StrikethroughSpan(), startIndex.pop(), output.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    private void handlerStartSIZE(Editable output, XMLReader xmlReader) {
        if (startIndex == null) {
            startIndex = new Stack<>();
        }
        startIndex.push(output.length());

        if (propertyValue == null) {
            propertyValue = new Stack<>();
        }

        propertyValue.push(getProperty(xmlReader, "value"));
    }

    private void handlerEndSIZE(Editable output) {

        if (!isEmpty(propertyValue)) {
            try {
                int value = Integer.parseInt(propertyValue.pop());
                output.setSpan(new AbsoluteSizeSpan(sp2px(MainApplication.getInstance(), value)), startIndex.pop(), output.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 利用反射获取html标签的属性值
     *
     * @param xmlReader
     * @param property
     * @return
     */
    private String getProperty(XMLReader xmlReader, String property) {
        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++) {
                // 这边的property换成你自己的属性名就可以了
                if (property.equals(data[i * 5 + 1])) {
                    return data[i * 5 + 4];
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 集合是否为空
     *
     * @param collection
     * @return
     */
    public static boolean isEmpty(Collection collection) {
        return collection == null || collection.isEmpty();
    }

    /**
     * 缩放独立像素 转换成 像素
     * @param context
     * @param spValue
     * @return
     */
    public static int sp2px(Context context, float spValue){
        return (int)(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,spValue,context.getResources().getDisplayMetrics())+0.5f);
    }
}
运行结果:


这里控制字体的大小并不是用font的size属性控制的(前面说了,font并不会进入TagHandler中),而是自己自定义了一个size标签里面定义了一个value属性(<size value='16'>字体大小</size>)进行控制。

这如果有小伙伴说我有执念,我就是想用font里面的font属性怎么办。不想再自定义一个size标签。额!

这个是有办法的。

java代码(这个类是实现小伙伴执念的关键类,来自于这里,英语好的可以自己看):

/**
 * Created by Siy on 2016/11/23.
 */


public class HtmlParser implements Html.TagHandler, ContentHandler
{
    //This approach has the advantage that it allows to disable processing of some tags while using default processing for others,
    // e.g. you can make sure that ImageSpan objects are not created:
    public interface TagHandler
    {
        // return true here to indicate that this tag was handled and
        // should not be processed further
        boolean handleTag(boolean opening, String tag, Editable output, Attributes attributes);
    }

    public static Spanned buildSpannedText(String html, TagHandler handler)
    {
        // add a tag at the start that is not handled by default,
        // allowing custom tag handler to replace xmlReader contentHandler
        return Html.fromHtml("<inject/>" + html, null, new HtmlParser(handler));
    }

    public static String getValue(Attributes attributes, String name)
    {
        for (int i = 0, n = attributes.getLength(); i < n; i++)
        {
            if (name.equals(attributes.getLocalName(i)))
                return attributes.getValue(i);
        }
        return null;
    }

    private final TagHandler handler;
    private ContentHandler wrapped;
    private Editable text;
    private ArrayDeque<Boolean> tagStatus = new ArrayDeque<>();

    private HtmlParser(TagHandler handler)
    {
        this.handler = handler;
    }

    @Override
    public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader)
    {
        if (wrapped == null)
        {
            // record result object
            text = output;

            // record current content handler
            wrapped = xmlReader.getContentHandler();

            // replace content handler with our own that forwards to calls to original when needed
            xmlReader.setContentHandler(this);

            // handle endElement() callback for <inject/> tag
            tagStatus.addLast(Boolean.FALSE);
        }
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes)
            throws SAXException
    {
        boolean isHandled = handler.handleTag(true, localName, text, attributes);
        tagStatus.addLast(isHandled);
        if (!isHandled)
            wrapped.startElement(uri, localName, qName, attributes);
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException
    {
        if (!tagStatus.removeLast())
            wrapped.endElement(uri, localName, qName);
        handler.handleTag(false, localName, text, null);
    }

    @Override
    public void setDocumentLocator(Locator locator)
    {
        wrapped.setDocumentLocator(locator);
    }

    @Override
    public void startDocument() throws SAXException
    {
        wrapped.startDocument();
    }

    @Override
    public void endDocument() throws SAXException
    {
        wrapped.endDocument();
    }

    @Override
    public void startPrefixMapping(String prefix, String uri) throws SAXException
    {
        wrapped.startPrefixMapping(prefix, uri);
    }

    @Override
    public void endPrefixMapping(String prefix) throws SAXException
    {
        wrapped.endPrefixMapping(prefix);
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException
    {
        wrapped.characters(ch, start, length);
    }

    @Override
    public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException
    {
        wrapped.ignorableWhitespace(ch, start, length);
    }

    @Override
    public void processingInstruction(String target, String data) throws SAXException
    {
        wrapped.processingInstruction(target, data);
    }

    @Override
    public void skippedEntity(String name) throws SAXException
    {
        wrapped.skippedEntity(name);
    }
}
java代码:

/**
 * Created by Siy on 2016/11/23.
 */

public class CustomerTagHandler_1 implements HtmlParser.TagHandler {
    /**
     * html 标签的开始下标
     */
    private Stack<Integer> startIndex;

    /**
     * html的标签的属性值 value,如:<size value='16'></size>
     * 注:value的值不能带有单位,默认就是sp
     */
    private Stack<String> propertyValue;

    @Override
    public boolean handleTag(boolean opening, String tag, Editable output, Attributes attributes) {
        if (opening) {
            handlerStartTAG(tag, output, attributes);
        } else {
            handlerEndTAG(tag, output, attributes);
        }
        return handlerBYDefault(tag);
    }

    private void handlerStartTAG(String tag, Editable output, Attributes attributes) {
        if (tag.equalsIgnoreCase("font")) {
            handlerStartFONT(output, attributes);
        } else if (tag.equalsIgnoreCase("del")) {
            handlerStartDEL(output);
        }
    }


    private void handlerEndTAG(String tag, Editable output, Attributes attributes) {
        if (tag.equalsIgnoreCase("font")) {
            handlerEndFONT(output);
        } else if (tag.equalsIgnoreCase("del")) {
            handlerEndDEL(output);
        }
    }

    private void handlerStartFONT(Editable output, Attributes attributes) {
        if (startIndex == null) {
            startIndex = new Stack<>();
        }
        startIndex.push(output.length());

        if (propertyValue == null) {
            propertyValue = new Stack<>();
        }

        propertyValue.push(HtmlParser.getValue(attributes, "size"));
    }

    private void handlerEndFONT(Editable output) {
        if (!isEmpty(propertyValue)) {
            try {
                int value = Integer.parseInt(propertyValue.pop());
                output.setSpan(new AbsoluteSizeSpan(sp2px(MainApplication.getInstance(), value)), startIndex.pop(), output.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    private void handlerStartDEL(Editable output) {
        if (startIndex == null) {
            startIndex = new Stack<>();
        }
        startIndex.push(output.length());
    }

    private void handlerEndDEL(Editable output) {
        output.setSpan(new StrikethroughSpan(), startIndex.pop(), output.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }


    /**
     * 返回true表示不交给系统后续处理
     * false表示交给系统后续处理
     *
     * @param tag
     * @return
     */
    private boolean handlerBYDefault(String tag) {
        if (tag.equalsIgnoreCase("del")) {
            return true;
        }
        return false;
    }
}
调用的java代码:
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView textView = (TextView) findViewById(R.id.testHtml);

        String htmlStr = "<font style=\"color:#ff6c00;font-size:18px\"> 1500/天</font> <font style=\"TEXT-DECORATION: line-through;" +
                "color:#808080;font-size:10px\">原价:20000元 </font>";

        String htmlStr_1 = "<font color='#ff6c00' size='20'> 1500/天</font> <del><font  color='#808080' size='12'>原价:20000元 </font></del>";

        String htmlStr_2 = "<font color='#ff6c00' size='4'> 1500/天</font> <strike><font  color='#808080' size='2'>原价:20000元 </font></strike>";

        String htmlStr_3 = "<font color='#ff6c00'> <size value='20'>1500/天</size></font> <del><font  color='#808080'><size value='12'>原价:20000元</size> </font></del>";

//        textView.setText(Html.fromHtml(htmlStr_3,null, new CustomerTagHandler()));

        textView.setText(HtmlParser.buildSpannedText(htmlStr_1,new CustomerTagHandler_1()));
    }
运行结果:


那为什么用HtmlParser就可以得到font标签,前面我不是说Html.fromHtml支持的标签不会进入TagHandler中吗!实力打自己的脸了,其实并不是的,大家看HtmlParser的第53行获取了默认的ContentHanler,然后第56行又把自己的ContentHandler设置了进去,然后在69行判断ishandler(HtmlParser.TagHandler的handleTag方法的返回值),如果ishandler是false就会执行默认的ContentHandler,也就是说我们在默认的ContentHandler处理之前就自己解析了html标签,当然就能获得font标签了。

本文中关于读取标签属性的方法来自于这里

  • 7
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
一、[Android实例]实现TextView里的文字有不同颜色 转eoe:http://www.eoeandroid.com/thread-4496-1-1.html import android.text.Html; TextView t3 = (TextView) findViewById(R.id.text3); t3.setText( Html.fromHtml( "<b>text3:</b> Text with a " + "<a href=\"http://www.google.com\">link</a> " + "created in the Java source code using HTML.")); 二、TextView显示html文件的图片 转javaeye:http://da-en.javaeye.com/blog/712415 我们知道要让TextView解析和显示Html代码。可以使用 Spanned text = Html.fromHtml(source); tv.setText(text); 来实现,这个用起来简单方便。 但是,怎样让TextView也显示Html<image>节点的图像呢? 我们可以看到fromHtml还有另一个重构: fromHtml(String source, Html.ImageGetter imageGetter, Html.TagHandler tagHandler) 实现一下ImageGetter就可以让图片显示了: ImageGetter imgGetter = new Html.ImageGetter() { @Override public Drawable getDrawable(String source) { Drawable drawable = null; drawable = Drawable.createFromPath(source); // Or fetch it from the URL // Important drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable .getIntrinsicHeight()); return drawable; } }; 至于TagHandler,我们这里不需要使用,可以直接传null。 参考文档: http://tech-droid.blogspot.com/2010/06/textview-with-html-content.html英语好的朋友就直接看英文文档吧。 三、Android---文字插入表情 转载自:http://blog.163.com/spf9190@126/blog/static/50207531201091545954587/ 这段时间在做一个短信项目,需要实现短信插入表情的功能,本一位非常困难,经过一段时间的研究,发现还是比较簡単的,现在总结如下。 以短信输入框为例,短信的输入框是一个EditText,它的append方法不仅可以加入字符串,还可以添加HTML标记。以下就是使用HTML标记添加表情的具体操作。 首先需要构建一个ImageGetter,作用是通过HTML标记获得对应在res目录下的图片: ImageGetter imageGetter = new ImageGetter() { @Override public Drawable getDrawable(String source) { int id = Integer.parseInt(source); //根据id从资源文件获取图片对象 Drawable d = getResources().getDrawable(id); d.setBounds(0, 0, d.getIntrinsicWidth(),d.getIntrinsicHeight()); return d; } }; 然后就可以直接往EditText视图添加 inputLable.append(Html.fromHtml("<img src='"+clickedImageId+"'/>", imageGetter, null)); 其 Html.fromHtml("<img src='"+clickedImageId+"'/>"就是HTML的图片标记,在Android支持了部分HTML标记的使用(这方面我还在继续研究),HTML标记必须被Html.fromHtml修饰。imageGetter即为之前创建的ImageGetter类型的对象。
Sun 官方 J2ee 5.0 教程 The Java EE 5Tutorial For Sun Java System Application Server 9.1 Contents Preface ..................................................................................................................................................29 Part I Introduction ........................................................................................................................................39 1 Overview ..............................................................................................................................................41 Java EE ApplicationModel ................................................................................................................. 42 DistributedMultitiered Applications ............................................................................................... 42 Security ......................................................................................................................................... 43 Java EE Components ................................................................................................................... 44 Java EE Clients .............................................................................................................................. 44 Web Components ........................................................................................................................ 46 Business Components ................................................................................................................. 47 Enterprise Information System Tier .......................................................................................... 48 Java EE Containers .............................................................................................................................. 48 Container Services ....................................................................................................................... 49 Container Types ........................................................................................................................... 49 Web Services Support ......................................................................................................................... 51 XML .............................................................................................................................................. 51 SOAP Transport Protocol ........................................................................................................... 52 WSDL Standard Format .............................................................................................................. 52 UDDI and ebXML Standard Formats ....................................................................................... 52 Java EE Application Assembly andDeployment ............................................................................. 52 Packaging Applications ...................................................................................................................... 53 Development Roles ............................................................................................................................. 54 Java EE Product Provider ............................................................................................................ 55 Tool Provider ............................................................................................................................... 55 Application Component Provider ............................................................................................. 55 3 Application Assembler ................................................................................................................ 56 ApplicationDeployer and Administrator ................................................................................. 56 Java EE 5 APIs ..................................................................................................................................... 57 Enterprise JavaBeans Technology .............................................................................................. 57 Java Servlet Technology .............................................................................................................. 58 JavaServer Pages Technology ..................................................................................................... 58 JavaServer Pages Standard Tag Library ..................................................................................... 58 JavaServer Faces ........................................................................................................................... 58 JavaMessage Service API ............................................................................................................ 59 Java Transaction API ................................................................................................................... 59 JavaMail API ................................................................................................................................ 59 JavaBeans Activation Framework .............................................................................................. 59 Java API for XML Processing ..................................................................................................... 60 Java API for XML Web Services (JAX-WS) .............................................................................. 60 Java Architecture for XML Binding (JAXB) ............................................................................. 60 SOAP with Attachments API for Java ........................................................................................ 60 Java API for XML Registries ....................................................................................................... 61 J2EE Connector Architecture ..................................................................................................... 61 JavaDatabase Connectivity API ................................................................................................. 61 Java Persistence API ..................................................................................................................... 62 JavaNaming and Directory Interface ........................................................................................ 62 Java Authentication and Authorization Service ....................................................................... 62 Simplified Systems Integration ................................................................................................... 63 Sun Java System Application Server Platform Edition 9 ................................................................. 63 Tools ............................................................................................................................................. 63 2 Using theTutorial Examples ..............................................................................................................65 Required Software ............................................................................................................................... 65 Tutorial Bundle ............................................................................................................................ 65 Java Platform, Standard Edition ................................................................................................. 66 Sun Java System Application Server 9.1 ..................................................................................... 66 NetBeans IDE ............................................................................................................................... 67 Apache Ant .................................................................................................................................. 68 Starting and Stopping the Application Server .................................................................................. 68 Starting the Admin Console ............................................................................................................... 69 Contents 4 The Java EE 5Tutorial • September 2007 Starting and Stopping the JavaDBDatabase Server ........................................................................ 69 Building the Examples ........................................................................................................................ 70 Building the Examples UsingNetBeans IDE ............................................................................ 70 Building the Examples on the Command-Line Using Ant ..................................................... 70 Tutorial Example Directory Structure .............................................................................................. 71 Debugging Java EE Applications ....................................................................................................... 72 Using the Server Log .................................................................................................................... 72 Using aDebugger ......................................................................................................................... 73 Part II TheWebTier ........................................................................................................................................ 75 3 Getting Started withWeb Applications ........................................................................................... 77 Web Applications ............................................................................................................................... 77 Web Application Life Cycle ................................................................................................................ 80 WebModules ...................................................................................................................................... 81 Packaging WebModules ............................................................................................................. 83 Deploying aWARFile ................................................................................................................. 84 TestingDeployed WebModules ................................................................................................ 85 ListingDeployed WebModules ................................................................................................. 86 Updating WebModules .............................................................................................................. 86 Undeploying WebModules ........................................................................................................ 88 Configuring Web Applications .......................................................................................................... 89 Mapping URLs to Web Components ........................................................................................ 89 Declaring Welcome Files ............................................................................................................ 91 Setting Initialization Parameters ................................................................................................ 92 Mapping Errors to Error Screens ............................................................................................... 93 Declaring Resource References .................................................................................................. 94 Duke’s Bookstore Examples ............................................................................................................... 96 AccessingDatabases from Web Applications .................................................................................. 97 Populating the ExampleDatabase ............................................................................................. 97 Creating aData Source in the Application Server .................................................................... 98 Further Information about Web Applications ................................................................................. 98 Contents 5 4 Java ServletTechnology .....................................................................................................................99 What Is a Servlet? ................................................................................................................................ 99 The Example Servlets ........................................................................................................................ 100 Troubleshooting Duke's BookstoreDatabase Problems ....................................................... 102 Servlet Life Cycle ............................................................................................................................... 102 Handling Servlet Life-Cycle Events ......................................................................................... 103 Handling Servlet Errors ............................................................................................................. 105 Sharing Information ......................................................................................................................... 105 Using Scope Objects .................................................................................................................. 105 Controlling Concurrent Access to Shared Resources ........................................................... 106 AccessingDatabases .................................................................................................................. 107 Initializing a Servlet ........................................................................................................................... 109 Writing ServiceMethods .................................................................................................................. 110 Getting Information from Requests ........................................................................................ 110 Constructing Responses ............................................................................................................ 112 Filtering Requests and Responses .................................................................................................... 114 Programming Filters .................................................................................................................. 115 Programming Customized Requests and Responses ............................................................ 117 Specifying FilterMappings ....................................................................................................... 119 Invoking Other Web Resources ....................................................................................................... 122 Including Other Resources in the Response ........................................................................... 122 Transferring Control to Another Web Component .............................................................. 124 Accessing the Web Context .............................................................................................................. 124 Maintaining Client State ................................................................................................................... 125 Accessing a Session .................................................................................................................... 125 Associating Objects with a Session .......................................................................................... 126 SessionManagement ................................................................................................................. 126 Session Tracking ........................................................................................................................ 127 Finalizing a Servlet ............................................................................................................................. 128 Tracking Service Requests ........................................................................................................ 129 NotifyingMethods to ShutDown ............................................................................................ 129 Creating Polite Long-RunningMethods ................................................................................. 130 Further Information about Java Servlet Technology .................................................................... 131 Contents 6 The Java EE 5Tutorial • September 2007 5 JavaServer PagesTechnology .........................................................................................................133 What Is a JSP Page? ............................................................................................................................ 133 A Simple JSP Page Example ...................................................................................................... 134 The Example JSP Pages ..................................................................................................................... 136 The Life Cycle of a JSP Page .............................................................................................................. 142 Translation and Compilation ................................................................................................... 142 Execution ................................................................................................................................... 143 Creating Static Content .................................................................................................................... 144 Response and Page Encoding ................................................................................................... 145 CreatingDynamic Content .............................................................................................................. 145 Using Objects within JSP Pages ................................................................................................ 145 Unified Expression Language .......................................................................................................... 146 Immediate andDeferred Evaluation Syntax ........................................................................... 148 Value andMethod Expressions ................................................................................................ 150 Defining a Tag Attribute Type .................................................................................................. 156 Deactivating Expression Evaluation ........................................................................................ 157 Literal Expressions ..................................................................................................................... 158 Resolving Expressions ............................................................................................................... 160 Implicit Objects .......................................................................................................................... 162 Operators ................................................................................................................................... 163 Reserved Words ......................................................................................................................... 163 Examples of EL Expressions ..................................................................................................... 164 Functions ................................................................................................................................... 165 JavaBeans Components .................................................................................................................... 167 JavaBeans ComponentDesign Conventions .......................................................................... 167 Creating and Using a JavaBeans Component ......................................................................... 168 Setting JavaBeans Component Properties .............................................................................. 169 Retrieving JavaBeans Component Properties ........................................................................ 171 Using Custom Tags ........................................................................................................................... 172 Declaring Tag Libraries ............................................................................................................. 172 Including the Tag Library Implementation ............................................................................ 174 Reusing Content in JSP Pages .......................................................................................................... 175 Transferring Control to Another Web Component ..................................................................... 176 jsp:param Element .................................................................................................................... 176 Including an Applet ........................................................................................................................... 176 Setting Properties for Groups of JSP Pages ..................................................................................... 179 Contents 7 Deactivating EL Expression Evaluation .................................................................................. 180 Further Information about JavaServer Pages Technology ........................................................... 183 6 JavaServer Pages Documents .........................................................................................................185 The Example JSPDocument ............................................................................................................ 185 Creating a JSPDocument ................................................................................................................. 188 Declaring Tag Libraries ............................................................................................................. 190 Including Directives in a JSPDocument ................................................................................. 191 Creating Static andDynamic Content .................................................................................... 193 Using the jsp:root Element .................................................................................................... 196 Using the jsp:output Element ................................................................................................ 196 Identifying the JSPDocument to the Container ............................................................................ 200 7 JavaServer Pages StandardTag Library ........................................................................................201 The Example JSP Pages ..................................................................................................................... 201 Using JSTL ......................................................................................................................................... 203 Tag Collaboration ...................................................................................................................... 204 Core Tag Library ............................................................................................................................... 205 Variable Support Tags ............................................................................................................... 205 Flow Control Tags ...................................................................................................................... 206 URL Tags .................................................................................................................................... 210 Miscellaneous Tags .................................................................................................................... 211 XML Tag Library ............................................................................................................................... 211 Core Tags ................................................................................................................................... 213 Flow Control Tags ...................................................................................................................... 214 Transformation Tags ................................................................................................................. 215 Internationalization Tag Library ..................................................................................................... 215 Setting the Locale ....................................................................................................................... 216 Messaging Tags .......................................................................................................................... 216 Formatting Tags ......................................................................................................................... 217 SQL Tag Library ................................................................................................................................ 218 query Tag Result Interface ........................................................................................................ 220 JSTL Functions ................................................................................................................................. 222 Further Information about JSTL ..................................................................................................... 223 Contents 8 The Java EE 5Tutorial • September 2007 8 CustomTags in JSP Pages .................................................................................................................225 What Is a Custom Tag? ..................................................................................................................... 226 The Example JSP Pages ..................................................................................................................... 226 Types of Tags ..................................................................................................................................... 229 Tags with Attributes ................................................................................................................... 229 Tags with Bodies ........................................................................................................................ 232 Tags ThatDefine Variables ....................................................................................................... 232 Communication between Tags ................................................................................................ 233 Encapsulating Reusable Content Using Tag Files ......................................................................... 233 Tag File Location ........................................................................................................................ 235 Tag File Directives ...................................................................................................................... 235 Evaluating Fragments Passed to Tag Files ............................................................................... 242 Custom Tag Examples ............................................................................................................... 243 Tag LibraryDescriptors .................................................................................................................... 247 Top-Level Tag LibraryDescriptor Elements .......................................................................... 248 Declaring Tag Files .................................................................................................................... 249 Declaring TagHandlers ............................................................................................................ 251 Declaring Tag Attributes for TagHandlers ............................................................................ 252 Declaring Tag Variables for TagHandlers .............................................................................. 254 Programming Simple TagHandlers ............................................................................................... 256 Including TagHandlers in Web Applications ........................................................................ 256 How Is a Simple TagHandler Invoked? .................................................................................. 256 TagHandlers for Basic Tags ..................................................................................................... 257 TagHandlers for Tags with Attributes .................................................................................... 257 TagHandlers for Tags with Bodies .......................................................................................... 260 TagHandlers for Tags ThatDefine Variables ........................................................................ 261 Cooperating Tags ....................................................................................................................... 263 TagHandler Examples .............................................................................................................. 265 9 Scripting in JSP Pages .......................................................................................................................273 The Example JSP Pages ..................................................................................................................... 273 Using Scripting ................................................................................................................................. 275 Disabling Scripting ............................................................................................................................ 275 JSPDeclarations ............................................................................................................................... 276 Initializing and Finalizing a JSP Page ....................................................................................... 276 Contents 9 JSP Scriptlets ..................................................................................................................................... 277 JSP Expressions ................................................................................................................................. 277 Programming Tags That Accept Scripting Elements .................................................................... 278 TLD Elements ............................................................................................................................. 278 TagHandlers .............................................................................................................................. 278 Tags with Bodies ........................................................................................................................ 280 Cooperating Tags ....................................................................................................................... 282 Tags ThatDefine Variables ....................................................................................................... 284 10 JavaServer FacesTechnology ..........................................................................................................285 JavaServer Faces Technology User Interface .................................................................................. 285 JavaServer Faces Technology Benefits ............................................................................................ 286 What Is a JavaServer Faces Application? ......................................................................................... 287 A Simple JavaServer Faces Application ........................................................................................... 287 Steps in theDevelopment Process ........................................................................................... 288 Mapping the FacesServlet Instance ...................................................................................... 289 Creating the Pages ...................................................................................................................... 290 Defining PageNavigation ......................................................................................................... 296 Configuring ErrorMessages ..................................................................................................... 297 Developing the Beans ................................................................................................................ 298 AddingManaged BeanDeclarations ....................................................................................... 298 User Interface ComponentModel .................................................................................................. 299 User Interface Component Classes .......................................................................................... 300 Component RenderingModel ................................................................................................. 301 ConversionModel ..................................................................................................................... 304 Event and ListenerModel ......................................................................................................... 305 ValidationModel ....................................................................................................................... 307 NavigationModel .............................................................................................................................. 307 Backing Beans ................................................................................................................................... 309 Creating a Backing Bean Class ................................................................................................. 309 The Life Cycle of a JavaServer Faces Page ....................................................................................... 313 Restore View Phase .................................................................................................................... 315 Further Information about JavaServer Faces Technology ............................................................ 318 Contents 10 The Java EE 5Tutorial • September 2007 11 Using JavaServer FacesTechnology in JSP Pages ........................................................................ 319 The Example JavaServer Faces Application .................................................................................... 319 Setting Up a Page ............................................................................................................................... 322 Using the Core Tags .......................................................................................................................... 325 Adding UI Components to a Page Using the HTML Component Tags ..................................... 327 UI Component Tag Attributes ................................................................................................. 327 Adding a Form Component ..................................................................................................... 329 Using Text Components ........................................................................................................... 330 Using Command Components for Performing Actions andNavigation ........................... 335 UsingData-Bound Table Components .................................................................................. 337 Adding Graphics and Images with the graphicImage Tag ................................................... 340 Laying Out Components with the UIPanel Component ...................................................... 341 Rendering Components for Selecting One Value .................................................................. 343 Rendering Components for SelectingMultiple Values ......................................................... 345 The UISelectItem, UISelectItems, and UISelectItemGroup Components ................... 346 Displaying ErrorMessages with the message and messages Tags ....................................... 349 Using LocalizedData ........................................................................................................................ 350 Loading a Resource Bundle ...................................................................................................... 351 Referencing Localized StaticData ............................................................................................ 352 Referencing ErrorMessages ..................................................................................................... 352 Using the Standard Converters ........................................................................................................ 354 Converting a Component’s Value ............................................................................................ 355 Using DateTimeConverter ....................................................................................................... 356 Using NumberConverter ........................................................................................................... 357 Registering Listeners on Components ............................................................................................ 359 Registering a Value-Change Listener on a Component ........................................................ 359 Registering an Action Listener on a Component ................................................................... 360 Using the Standard Validators ......................................................................................................... 361 Validating a Component’s Value ............................................................................................. 362 Using the LongRangeValidator .............................................................................................. 363 Binding Component Values and Instances to ExternalData Sources ........................................ 364 Binding a Component Value to a Property ............................................................................. 365 Binding a Component Value to an Implicit Object ............................................................... 366 Binding a Component Instance to a Bean Property .............................................................. 368 Binding Converters, Listeners, and Validators to Backing Bean Properties .............................. 369 Referencing a Backing BeanMethod .............................................................................................. 370 Contents 11 Referencing aMethod That PerformsNavigation ................................................................. 371 Referencing aMethod ThatHandles an Action Event .......................................................... 371 Referencing aMethod That Performs Validation .................................................................. 372 Referencing aMethod ThatHandles a Value-change Event ................................................ 372 Using Custom Objects ...................................................................................................................... 373 Using a Custom Converter ....................................................................................................... 374 Using a Custom Validator ......................................................................................................... 375 Using a Custom Component .................................................................................................... 376 12 Developing with JavaServer FacesTechnology ...........................................................................379 Writing Bean Properties ................................................................................................................... 379 Writing Properties Bound to Component Values ................................................................. 380 Writing Properties Bound to Component Instances ............................................................. 388 Writing Properties Bound to Converters, Listeners, or Validators ..................................... 389 Performing Localization ................................................................................................................... 390 Creating a Resource Bundle ...................................................................................................... 390 LocalizingDynamicData .......................................................................................................... 390 LocalizingMessages ................................................................................................................... 391 Creating a Custom Converter .......................................................................................................... 393 Implementing an Event Listener ..................................................................................................... 395 Implementing Value-Change Listeners .................................................................................. 396 Implementing Action Listeners ............................................................................................... 397 Creating a Custom Validator ........................................................................................................... 398 Implementing the Validator Interface ..................................................................................... 399 Creating a Custom Tag .............................................................................................................. 402 Writing Backing BeanMethods ...................................................................................................... 404 Writing aMethod toHandleNavigation ................................................................................ 404 Writing aMethod toHandle an Action Event ........................................................................ 406 Writing aMethod to Perform Validation ............................................................................... 406 Writing aMethod toHandle a Value-Change Event ............................................................. 407 13 Creating CustomUI Components ...................................................................................................409 Determining Whether YouNeed a Custom Component or Renderer ....................................... 410 When to Use a Custom Component ........................................................................................ 410 When to Use a Custom Renderer ............................................................................................. 411 Contents 12 The Java EE 5Tutorial • September 2007 Component, Renderer, and Tag Combinations ..................................................................... 412 Understanding the ImageMap Example ........................................................................................ 413 Why Use JavaServer Faces Technology to Implement an ImageMap? ............................... 413 Understanding the Rendered HTML ...................................................................................... 413 Understanding the JSP Page ..................................................................................................... 414 ConfiguringModelData ........................................................................................................... 416 Summary of the Application Classes ....................................................................................... 417 Steps for Creating a Custom Component ....................................................................................... 418 Creating Custom Component Classes ............................................................................................ 419 Specifying the Component Family .......................................................................................... 421 Performing Encoding ................................................................................................................ 422 PerformingDecoding ................................................................................................................ 424 Enabling Component Properties to Accept Expressions ...................................................... 424 Saving and Restoring State ........................................................................................................ 426 Delegating Rendering to a Renderer ............................................................................................... 427 Creating the Renderer Class ..................................................................................................... 427 Identifying the Renderer Type ................................................................................................. 429 Handling Events for Custom Components .................................................................................... 429 Creating the Component TagHandler ........................................................................................... 430 Retrieving the Component Type .............................................................................................. 431 Setting Component Property Values ....................................................................................... 431 Providing the Renderer Type ................................................................................................... 433 Releasing Resources ................................................................................................................... 434 Defining the Custom Component Tag in a Tag LibraryDescriptor ........................................... 434 14 Configuring JavaServer Faces Applications ..................................................................................437 Application Configuration Resource File ....................................................................................... 437 Configuring Beans ............................................................................................................................. 439 Using the managed-bean Element ............................................................................................ 439 Initializing Properties Using the managed-property Element ............................................ 441 InitializingMaps and Lists ........................................................................................................ 447 Registering Custom ErrorMessages ............................................................................................... 448 Registering Custom Localized Static Text ...................................................................................... 449 Registering a Custom Validator ....................................................................................................... 450 Registering a Custom Converter ..................................................................................................... 451 Contents 13 ConfiguringNavigation Rules ......................................................................................................... 451 Registering a Custom Renderer with a Render Kit ........................................................................ 455 Registering a Custom Component .................................................................................................. 457 Basic Requirements of a JavaServer Faces Application ................................................................. 458 Configuring an Application with aDeploymentDescriptor ................................................ 459 Including the Required JAR Files ............................................................................................. 466 Including the Classes, Pages, and Other Resources ............................................................... 466 15 Internationalizing and LocalizingWeb Applications ..................................................................467 Java Platform Localization Classes .................................................................................................. 467 Providing LocalizedMessages and Labels ...................................................................................... 468 Establishing the Locale .............................................................................................................. 468 Setting the Resource Bundle ..................................................................................................... 469 Retrieving LocalizedMessages ................................................................................................. 470 Date andNumber Formatting ......................................................................................................... 471 Character Sets and Encodings .......................................................................................................... 472 Character Sets ............................................................................................................................. 472 Character Encoding ................................................................................................................... 473 Further Information about Internationalizing Web Applications .............................................. 475 Part III Web Services .....................................................................................................................................477 16 BuildingWeb Services with JAX-WS ...............................................................................................479 Setting the Port .................................................................................................................................. 480 Creating a Simple Web Service and Client with JAX-WS ............................................................ 480 Requirements of a JAX-WS Endpoint ..................................................................................... 481 Coding the Service Endpoint Implementation Class ............................................................ 482 Building, Packaging, andDeploying the Service .................................................................... 482 Testing the Service without a Client ........................................................................................ 484 A Simple JAX-WS Client ........................................................................................................... 484 Types Supported by JAX-WS ........................................................................................................... 486 Web Services Interoperability and JAX-WS .................................................................................. 487 Further Information about JAX-WS ............................................................................................... 487 Contents 14 The Java EE 5Tutorial • September 2007 17 Binding between XML Schema and Java Classes ......................................................................... 489 JAXB Architecture ............................................................................................................................. 489 ArchitecturalOverview ............................................................................................................. 489 The JAXB Binding Process ........................................................................................................ 490 More about Unmarshalling ...................................................................................................... 492 More aboutMarshalling ............................................................................................................ 492 More about Validation .............................................................................................................. 492 Representing XML Content ............................................................................................................. 492 Java Representation of XML Schema ....................................................................................... 492 Binding XML Schemas ..................................................................................................................... 493 Simple TypeDefinitions ............................................................................................................ 493 DefaultData Type Bindings ..................................................................................................... 493 Customizing Generated Classes and Java Program Elements ..................................................... 495 Schema-to-Java .......................................................................................................................... 495 Java-to-Schema .......................................................................................................................... 496 JAXB Examples ................................................................................................................................. 501 JAXB Compiler Options ........................................................................................................... 503 JAXB Schema Generator Option ............................................................................................. 505 About the Schema-to-Java Bindings ........................................................................................ 505 Schema-Derived JAXB Classes ................................................................................................. 508 Basic JAXB Examples ........................................................................................................................ 511 ModifyMarshal Example .......................................................................................................... 511 Unmarshal Validate Example ................................................................................................... 512 Customizing JAXB Bindings ............................................................................................................ 514 Why Customize? ........................................................................................................................ 515 CustomizationOverview .......................................................................................................... 515 Customize Inline Example ........................................................................................................ 526 Datatype Converter Example ................................................................................................... 531 BindingDeclaration Files .......................................................................................................... 533 External Customize Example ................................................................................................... 536 Java-to-Schema Examples ................................................................................................................ 536 CreateMarshal Example ........................................................................................................... 537 XmlAccessorOrder Example .................................................................................................... 538 XmlAdapter Field Example ...................................................................................................... 540 XmlAttribute Field Example ..................................................................................................... 543 XmlRootElement Example ....................................................................................................... 544 Contents 15 XmlSchemaType Class Example .............................................................................................. 545 XmlType Example ..................................................................................................................... 546 Further Information about JAXB .................................................................................................... 548 18 Streaming API for XML ......................................................................................................................549 Why StAX? ........................................................................................................................................ 549 Streaming versusDOM ............................................................................................................. 549 Pull Parsing versus Push Parsing .............................................................................................. 550 StAX Use Cases .......................................................................................................................... 551 Comparing StAX to Other JAXP APIs .................................................................................... 551 StAX API ........................................................................................................................................... 552 Cursor API ................................................................................................................................. 553 Iterator API ................................................................................................................................ 553 Choosing between Cursor and Iterator APIs .......................................................................... 557 Using StAX ........................................................................................................................................ 559 StAX Factory Classes ................................................................................................................. 559 Resources,Namespaces, and Errors ........................................................................................ 561 Reading XML Streams ............................................................................................................... 561 Writing XML Streams ............................................................................................................... 564 Sun’s Streaming XML Parser Implementation .............................................................................. 566 Reporting CDATA Events ......................................................................................................... 566 Streaming XML Parser Factories Implementation ................................................................ 566 Example Code ................................................................................................................................... 567 Example Code Organization .................................................................................................... 567 Example XMLDocument ......................................................................................................... 568 Cursor Example .......................................................................................................................... 568 Cursor-to-Event Example ......................................................................................................... 571 Event Example ............................................................................................................................ 573 Filter Example ............................................................................................................................ 575 Read-and-Write Example ......................................................................................................... 578 Writer Example .......................................................................................................................... 580 Further Information about StAX ..................................................................................................... 583 19 SOAP with Attachments API for Java ............................................................................................. 585 Overview of SAAJ .............................................................................................................................. 586 Contents 16 The Java EE 5Tutorial • September 2007 SAAJMessages ........................................................................................................................... 586 SAAJ Connections ..................................................................................................................... 589 SAAJ Tutorial .................................................................................................................................... 590 Creating and Sending a SimpleMessage ................................................................................. 591 Adding Content to theHeader ................................................................................................. 598 Adding Content to the SOAPPart Object ................................................................................. 599 Adding aDocument to the SOAP Body .................................................................................. 600 ManipulatingMessage Content Using SAAJ orDOMAPIs ................................................ 601 Adding Attachments .................................................................................................................. 601 Adding Attributes ...................................................................................................................... 603 Using SOAP Faults ..................................................................................................................... 608 Code Examples ................................................................................................................................. 613 Request Example ........................................................................................................................ 613 Header Example ......................................................................................................................... 614 DOMandDOMSource Examples ........................................................................................... 617 Attachments Example ............................................................................................................... 622 SOAP Fault Example ................................................................................................................. 624 Further Information about SAAJ .................................................................................................... 627 Part IV Enterprise Beans ...............................................................................................................................629 20 Enterprise Beans ...............................................................................................................................631 What Is an Enterprise Bean? ............................................................................................................ 631 Benefits of Enterprise Beans ..................................................................................................... 631 When to Use Enterprise Beans ................................................................................................. 632 Types of Enterprise Beans ......................................................................................................... 632 What Is a Session Bean? .................................................................................................................... 633 StateManagementModes ......................................................................................................... 633 When to Use Session Beans ...................................................................................................... 634 What Is aMessage-Driven Bean? .................................................................................................... 634 WhatMakesMessage-Driven Beans Different fr
Android Studio是一款用于开发Android应用程序的集成开发环境(IDE)。其html.fromhtmlAndroid Studio提供的一个方法,用于将HTML格式的字符串转换成可显示的文本。 html.fromhtml方法通过解析HTML代码,并将其转换为Spanned对象。Spanned对象是一个包含了不同样式(如字体、颜色、格式等)的文本对象,可以在Android应用进行渲染和显示。 使用html.fromhtml方法非常简单,只需要将需要转换的HTML代码作为参数传入即可。例如,如果我们有一个包含HTML标签的字符串: String htmlString = "<h1>这是标题<h1><p>这是正文</p>"; Spanned spannedText = Html.fromHtml(htmlString); 通过这两行代码,我们就可以将HTML格式的字符串转换为可供Android应用程序渲染和显示的文本对象。我们可以将该对象设置到TextView或其他支持Spanned对象显示的组件。例如: TextView textView = findViewById(R.id.textview); textView.setText(spannedText); 这样,我们就可以在应用看到经过HTML格式化后的文本内容。 需要注意的是,html.fromhtml方法默认只支持部分HTML标签的解析,比如<h1>、<p>等常见标签。如果需要支持更多标签或自定义样式,可以为html.fromhtml方法提供一个Html.TagHandler对象的实例,通过对HTML标签进行处理来实现自定义样式的显示。 总之,android studio的html.fromhtml方法提供了方便的功能,可以将HTML格式的字符串转换为Spanned对象,并在Android应用程序进行显示和渲染。这为我们开发具有丰富文本显示需求的应用程序提供了一种简单的方式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值