Android EditText: How to create an empty bullet paragraph by BulletSpan?

吃可爱长大的小学妹 提交于 2019-12-04 04:04:14

It is an ugly solution, but I have not found any better - try adding an empty character in the end (something like zero-width space). This is producing the result you'd like (at least visually):

public void setBulletText(EditText myEdit, String text) {
        String[] lines = TextUtils.split(text, "\n");
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
        String line = null;
        for (int index = 0; index < lines.length; ++index) {
            line = lines[index];
            int length = spannableStringBuilder.length();
            spannableStringBuilder.append(line);
            if (index != lines.length - 1) {
                spannableStringBuilder.append("\n");
            } else if (TextUtils.isEmpty(line)) {
                spannableStringBuilder.append("\u200B");
            }
            spannableStringBuilder.setSpan(new BulletSpan(30), length, length + 1,
                Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        }
        myEdit.setText(spannableStringBuilder);
    }

The result is:

Ideally I'd make a custom EditText class which appends this character internally, but removes it when the text is being sent to any other object.

Is this good?

EditText myEdit = (EditText) this.findViewById(R.id.myedit);
myEdit.setText("a\nb\n\n");
Spannable s = myEdit.getText();
s.setSpan(new BulletSpan(30), 0, 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
s.setSpan(new BulletSpan(30), 2, 3, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
s.setSpan(new BulletSpan(30), 4, 5, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
myEdit.setText(s);
myEdit.setSelection(s.length()-1);

The result is

blganesh101

I have a simple solution to this, just add a space at the end of the newline

EditText myEdit = (EditText) this.findViewById(R.id.myedit);
myEdit.setText("a\nb\n "); //notice the space after newline
Spannable s = myEdit.getText();
s.setSpan(new BulletSpan(30), 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
s.setSpan(new BulletSpan(30), 2, 3, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
s.setSpan(new BulletSpan(30), 4, 4, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
myEdit.setText(s);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!