Android:使用LeadingMarginSpan在textview中显示项目符号列表?

时间:2015-12-04 01:33:38

标签: java android textview android-xml

我想在textview中显示项目符号列表。我可以使用子弹,但子弹不是很有吸引力,似乎没有办法定制它。我想使用默认项目符号(•)作为我的项目符号列表。有没有办法使用LeadingMarginSpan来获得我想要的效果?基本上,如果线条以子弹开头,我希望它与左边对齐,但是如果线条太长以至于它断开那么下一行向下的文本(断开的文本)应该缩进到与之后的文本相同的级别要点。

* for example
instead of this

* for example
  should look like this

我目前的代码:

String[] bulletpoint = {some array of strings};
CharSequence allText = "";

for (int i = 0; i < bulletpoint.length; i++) {
    String text = bulletpoint[i];
    SpannableString s = new SpannableString(text + "\n");
    s.setSpan(new LeadingMarginSpan(BulletSpan.STANDARD_GAP_WIDTH) {
        @Override
        public int getLeadingMargin(boolean first) {
            return 0;
        }
        @Override
        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 layout) {

        }
    }, 0, text.length(), 0);
    allText = TextUtils.concat(allText, s);
}
textview.settext(allText);

2 个答案:

答案 0 :(得分:5)

回答代码示例:

CharSequence allText = "";
for (String aBulletpoint : bulletpoint) {
    String text = aBulletpoint.trim() + ".";
    SpannableString spannableString = new SpannableString(text + "\n");
    spannableString.setSpan(new LeadingMarginSpan() {
        @Override
        public int getLeadingMargin(boolean first) {
            return getString(R.string.bulletpoint).length() * 50;
        }
        @Override
        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 layout) {
            if (first) {
                Paint.Style orgStyle = p.getStyle();
                p.setStyle(Paint.Style.FILL);
                c.drawText(getString(R.string.bulletpoint) + " ", 0, bottom - p.descent(), p);
                p.setStyle(orgStyle);
            }
         }
    }, 0, text.length(), 0);
    allText = TextUtils.concat(allText, spannableString);
}
someTextView.setText(allText);

答案 1 :(得分:2)

您可以使用BulletSpanLeadingMarginSpan实施,只需覆盖drawLeadingMargin()即可按照您想要的方式绘制项目符号。

请参阅BulletSpan的代码,了解他们如何绘制子弹并将其用作指南:

BulletSpan source code