简体   繁体   中英

Android: Creating bullet point list in an Edit Text

I am using an EditText as the main notepad typing area and I want the user to be able to simply click a button and have their note turn into a bullet point list (add the bullet points and a few spaces before the text of each line).

I have figured out something that works, but my main problem is that if the user has a double-newline (a blank line in the note) it adds a bullet point to the empty line.

I tried using Matcher and Pattern with regular expressions, but don't cannot figure out how to avoid adding bullet points to a blank line in an already created set of text.

Here is the code that adds the bullet point to every line except the note title.

//Place text into an array containing the lines.
String[] lines = noteText.split("\n");

for (int i = 0; i < lines.length; i++) {
    //The note title. Don't add a bullet point
    if(i == 0) {
        pad.setText(lines[i]);
    } else {
        pad.append("\n" + "\u2022" + "  " + lines[i]);
    }
}

Why not check each line and see if it is empty or white text only?

String[] lines = noteText.split("\n");

for (int i = 0; i < lines.length; i++) {
 //The note title. Don't add a bullet point
 if(i == 0) {
    pad.setText(lines[i]);
 } else if (TextUtils.isEmpty(lines[i].trim()) {
    pad.setText(lines[i]);
 } else {
    pad.append("\n" + "\u2022" + "  " + lines[i]);
 }
}

Also, it will be better to simply handle i=0 case outside the loop and not inside. Otherwise you performing the zero check for every iteration which is unnecessary.

If you want something this complicated you may be better off not using an EditText, but writing your own custom view.

Ignoring that, here's a hack that will probably work

str = str.replaceAll("\n*","\n");

That will replace all double, triple, or more than that newlines with a single newline. If you need the newlines, try

str = str.replaceAll("\n{1}", "\n\u2022");

That will look for single newlines and replace them with a newline followed by your bullet point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM