2016-12-06 25 views
1

我想在android文本中顯示項目符號。我已經成功添加了它們。 我在互聯網上搜索,發現你可以添加子彈。但如果文本不止一行,它不會像HTML列表那樣遵循適當的間距。在Android中添加適當格式的項目符號

請看下面的截圖。

enter image description here

我用下面的代碼添加項目符號。

String longDescription = "Enhanced bass performance.\n" + 
       "Lightweight headband enhances comfort and adds durability\n" + 
       "Easy to adjust headband ensures optimum fit and comfort\n" + 
       "2 metre-long cable"; 

     String arr[] = longDescription.split("\n"); 
     StringBuilder desc = new StringBuilder(); 
     for (String s : arr){ 
      desc.append("<li>"+s+"</li>"); 
     } 
     String newDesc = "<ul>"+desc+"</ul>"; 

     tvProdDesc.setText(Html.fromHtml(newDesc, null, new UlTagHandler())); 

這裏是我的

UlTagHandler.java

public class UlTagHandler implements Html.TagHandler { 

    public void handleTag(boolean opening, String tag, Editable output, 
          XMLReader xmlReader) { 
     if(tag.equals("ul") && !opening) output.append("\n"); 
     if(tag.equals("li") && opening) output.append("\n•\t"); 
    } 
} 

但我想文本應被正確格式化,像文字處理一樣。

我想這種類型的輸出

enter image description here

我們可以做任何事情,呈三角以上的圖像?

+0

沒有它不復制見我加入了子彈。我想要格式良好的文字。 –

+0

你提供什麼minSdk? – deadfish

+0

minSdkVersion 16 and targetSdkVersion 23 –

回答

4

你會滿意這個例子嗎?

public class MainActivity extends AppCompatActivity { 

    private TextView tvProdDesc; 

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

     tvProdDesc = (TextView) findViewById(R.id.text1); 

     String longDescription = "Enhanced bass performance.\n" + 
       "Lightweight headband enhances comfort and adds durability\n" + 
       "Easy to adjust headband ensures optimum fit and comfort\n" + 
       "2 metre-long cable"; 

     String arr[] = longDescription.split("\n"); 

     int bulletGap = (int) dp(10); 

     SpannableStringBuilder ssb = new SpannableStringBuilder(); 
     for (int i = 0; i < arr.length; i++) { 
      String line = arr[i]; 
      SpannableString ss = new SpannableString(line); 
      ss.setSpan(new BulletSpan(bulletGap), 0, line.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 
      ssb.append(ss); 

      //avoid last "\n" 
      if(i+1<arr.length) 
       ssb.append("\n"); 

     } 

     tvProdDesc.setText(ssb); 
    } 

    private float dp(int dp) { 
     return getResources().getDisplayMetrics().density * dp; 
    } 
} 

結果:

enter image description here

相關問題