Add Bullets with proper formatting in Android

情到浓时终转凉″ 提交于 2020-01-24 22:48:09

问题


I wanted to show bullets in android text. I have added them successfully. I search over internet and found that you can add bullets. but if text goes more than one line it does not follow proper spacing like html list does.

See Screenshot below.

I have used following code to add bullets.

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

Here is my

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

But I want text should be properly formatted like word processor does.

I want this type of output

Can we do anything simillar to above image?


回答1:


Would You be satisfied of this example?

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

Result:



来源:https://stackoverflow.com/questions/40990755/add-bullets-with-proper-formatting-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!