+3

Support List tag of HTML in TextView using fromHtml()

There is a lovely method on the android.text.Html class, fromHtml(), that converts HTML into a Spannable for use with a TextView.

TextView textView = (TextView) findViewById(R.id.textView1);
//class ListTagHandler will be used here.
textView.setText(Html.fromHtml(newsText, null, new ListTagHandler()));

public class ListTagHandler implements TagHandler {
        private int                             index   = 0;
        private List<String>    parents = new ArrayList<String>();

        /* (non-Javadoc)
         * @see android.text.Html.TagHandler#handleTag(boolean, java.lang.String, android.text.Editable, org.xml.sax.XMLReader)
         */
        @Override
        public void handleTag(final boolean opening, final String tag, Editable output,
                        final XMLReader xmlReader) {
                if (tag.equals("ul") || tag.equals("ol") || tag.equals("dd")) {
                        if (opening) {
                                parents.add(tag);
                        } else
                                parents.remove(tag);

                        index = 0;
                } else if (tag.equals("li") && !opening)
                        handleListTag(output);
        }

        /**
         * @param output
         */
        private void handleListTag(Editable output) {
                if (parents.get(parents.size() - 1).equals("ul")) {
                        output.append("\n");
                        String[] split = output.toString().split("\n");

                        int lastIndex = split.length - 1;
                        int start = output.length() - split[lastIndex].length() - 1;
                        output.setSpan(new BulletSpan(15 * parents.size()), start, output.length(), 0);
                } else if (parents.get(parents.size() - 1).equals("ol")) {
                        index++;

                        output.append("\n");
                        String[] split = output.toString().split("\n");

                        int lastIndex = split.length - 1;
                        int start = output.length() - split[lastIndex].length() - 1;
                        output.insert(start, index + ". ");
                        output.setSpan(new LeadingMarginSpan.Standard(15 * parents.size()), start,
                                        output.length(), 0);
                }
        }
}

All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí