Force next word to a new line if the word is too long for the textview Force next word to a new line if the word is too long for the textview xml xml

Force next word to a new line if the word is too long for the textview


First you can get the text paint using TextView.getPaint(), then each time you add a new word(Hi, I, am, etc), call measureText on the paint. If the result length is longer than the available width of your TextView, add a \n before the new word.Reset the data and repeat the steps.


I ended up using

private void initView() {        Paint paint = new Paint();        float width = paint.measureText(mQuestion);        int maxLength = 300; // put whatever length you need here        if (width > maxLength) {            List<String> arrayList = null;            String[] array = (mQuestion.split("\\s"));            arrayList = Arrays.asList(array);            int seventyPercent = (int) (Math.round(arrayList.size() * 0.70)); // play with this if needed            String linebreak = arrayList.get(seventyPercent) + "\n";            arrayList.set(seventyPercent, linebreak);            mQuestion = TextUtils.join(" ", arrayList);            mQuestion.replace(",", " ");        }        mQuestionHolderTextView.setText(mQuestion);    }

I measure the string, turn it into a List, then split it at 70% and make a new line. Then I turn the List back into a String and remove the commas. As long as the word is no more than 30% of the remaining line you're in the clear, otherwise adjust accordingly.

It's quick and dirty, but it worked for me.


Using following method you can get the wrapped text.

As I don't have android set up, so I have written a Test class and called the method from main. You need to pass textview width. I passed 14 here.

    public class Test{    public static void main(String[] args) {        String wrappedText=wrapText(14);        System.out.println(wrappedText);    }    public static String wrapText(int textviewWidth) {        String mQuestion = "Hi I am an example of a string that is breaking correctly on words";        String temp = "";        String sentence = "";        String[] array = mQuestion.split(" "); // split by space        for (String word : array) {            if ((temp.length() + word.length()) < textviewWidth) {  // create a temp variable and check if length with new word exceeds textview width.                temp += " "+word;            } else {                sentence += temp+"\n"; // add new line character                temp = word;            }        }        return (sentence.replaceFirst(" ", "")+temp);    }}

Output -

Hi I am anexample of astring that isbreakingcorrectly onwords