在Android中添加具有适当格式的项目符号

时间:2016-12-06 08:20:42

标签: android user-interface html-lists formatted-text

我想在Android文本中显示子弹。我已成功添加它们。 我通过互联网搜索,发现你可以添加子弹。但是如果文本超过一行,它就不像html列表那样遵循适当的间距。

见下面的截图。

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

我们可以对上面的图像做任何事吗?

1 个答案:

答案 0 :(得分: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