在 Android 中添加格式正确的项目符号

Add Bullets with proper formatting in Android

我想在 android 文本中显示项目符号。我已成功添加它们。 我在互联网上搜索,发现您可以添加项目符号。但是如果文本超过一行,它就不会像 html 列表那样遵循适当的间距。

见下面的截图。

我使用了以下代码来添加项目符号。

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");
    }
}

但我希望文本的格式应该像文字处理器一样正确。

我想要这种类型的输出

我们可以做类似上图的事情吗?

您对这个例子满意吗?

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;
    }
}

结果: