Samuel909 Samuel909 - 5 months ago 9
Android Question

Detect space between second and third word and move words to next line

I have a list of names in an Adapter. When the name is being highlighted and if the name is too long (more than 2 words), I need to move the words after the gap of second word to next line in such a way that the words moved in new line maintain same space with the next name in Adapter.

The example is, consider the list of names in the list as -


. Alex

. Martin Kooper Well

. Thomas


(As you see, when first name is highlighted, since it is less than 2 words, I dont need to anything)

Now,


. Alex

. Martin Kooper

Well

. Thomas


(As you see, when second name is highlighted, since it is more than 2 words, I need to put the third word
Well
in next line. It should maintain same spacing with next element Thomas in the list)

sJy sJy
Answer

Try

    String name = "some person name".trim();
    if(name.indexOf(" ") != name.lastIndexOf(" ")) {
        int secondSpacePos = name.indexOf(" ", name.indexOf(" ") + 1);
        name = name.substring(0, secondSpacePos) + "\n " + name.substring(secondSpacePos);
    }