3

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

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

我想要这种类型的输出

在此处输入图像描述

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

4

1 回答 1

10

你对这个例子满意吗?

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

结果:

在此处输入图像描述

于 2016-12-06T09:00:29.610 回答