2015-12-04 148 views
1

我想在textview中顯示一個項目符號列表。我可以使用子彈頭彈,但子彈不是很有吸引力,似乎也沒有定製它的方法。我想爲我的項目符號列表使用默認的項目符號(•)。有沒有使用LeadingMarginSpan獲得我想要的效果的方法?基本上,如果行以子彈開頭,我希望它與左邊對齊,但是如果行太長以至於它斷開,那麼下一行的文本(斷開的文本)應該縮進到與文本之後的文本相同的級別子彈點。Android:使用LeadingMarginSpan在textview中顯示項目符號列表?

* 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); 

回答

4

回答與代碼示例:

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); 
2

您可以使用BulletSpanLeadingMarginSpan實施,只是重寫drawLeadingMargin()繪製子彈你想要的確切方式。

參考代碼BulletSpan看他們如何繪製子彈和使用,作爲指導:

BulletSpan source code

相關問題