[Solved] How to format single textview like below in android without using \n or html format?


You can do it programmatically using this function

val text = "This is my first text view this is my second textview this is my third textview"
textView.text = proxyWifi.textFormation(text)

copy/paste this code do your project 🙂

public String textFormation(String text){
    String result = "";
    String[] sentenceWords = text.split(" ");
    List<String> newSentenceWords = new ArrayList<>();
    textRec(sentenceWords, newSentenceWords, sentenceWords.length -1, 0, "");

    int spacing = 0;
    for(int i = newSentenceWords.size() -1 ; i >= 0 ; i--){
        if(i == newSentenceWords.size() -1)
            result = newSentenceWords.get(i);
        else{
            result += "\n";
            spacing += (newSentenceWords.get(i + 1).length() - newSentenceWords.get(i).length())/2;

            for(int j = 0 ; j < spacing ; j++){
                result += " ";
            }

            result += newSentenceWords.get(i);
        }
    }

    return result;

}

public void textRec(String[] words, List<String> newWords, int indexWords, int indexNewWords, String sentence){
    Log.e("sentence", sentence);
    if(indexWords >= 0){
        if(indexNewWords == 0) {
            newWords.add(words[indexWords]);
            textRec(words, newWords, indexWords - 1, ++indexNewWords, "");
        }else{
            if(newWords.get(indexNewWords - 1).length() >= sentence.length())
                if(sentence.isEmpty())
                    textRec(words, newWords, indexWords - 1, indexNewWords, words[indexWords]);
                else
                    textRec(words, newWords, indexWords - 1, indexNewWords,  words[indexWords] + " " + sentence);
            else {
                newWords.add(sentence);
                textRec(words, newWords, indexWords , ++indexNewWords, "");
            }
        }
    }else{
        if(sentence.isEmpty()){
            return;
        }else{
            newWords.set(indexNewWords - 1 ,sentence + " " + newWords.get(indexNewWords - 1)) ;
        }
    }
}

OUTPUT
enter image description here

solved How to format single textview like below in android without using \n or html format?