Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordered lists inside an Android TextView

I want to display an ordered list inside a TextView, for example:
1) item 1
2) item 2

Using the following layout:

<TextView
    android:text="<ol><li>item 1\n</li><li>item 2\n</li></ol>
    />

I get:

  • item 1
  • item 2

How can I change the bullets to numbers?

Thanks.

like image 609
Yoav Epstein Avatar asked Feb 04 '10 00:02

Yoav Epstein


1 Answers

I think you have to do this in code. I had to subclass LeadingMarginSpan to get this to work. Here is how I did it.

private class NumberIndentSpan implements LeadingMarginSpan {

    private final int gapWidth;
    private final int leadWidth;
    private final int index;

    public NumberIndentSpan(int leadGap, int gapWidth, int index) {
        this.leadWidth = leadGap;
        this.gapWidth = gapWidth;
        this.index = index;
    }

    public int getLeadingMargin(boolean first) {
        return leadWidth + gapWidth;
    }

    public void drawLeadingMargin(Canvas c, Paint p, int x, int dir, int top, int baseline, int bottom, CharSequence text, int start, int end, boolean first, Layout l) {
        if (first) {
            Paint.Style orgStyle = p.getStyle();
            p.setStyle(Paint.Style.FILL);
            float width = p.measureText("4.");
            c.drawText(index + ".", (leadWidth + x - width / 2) * dir, bottom - p.descent(), p);
            p.setStyle(orgStyle);
        }
    }
}

Get hold of your view, and use it like this:

SpannableStringBuilder content = new SpannableStringBuilder();
for(String text : list) {
    int contentStart = content.length();
    content.append(text);
    content.setSpan(new NumberIndentSpan(15, 15, number), contentStart, content.length(), 0);
}

TextView view = findViewById(R.id.....);
view.setText(content);
like image 110
Håvard Avatar answered Oct 04 '22 19:10

Håvard