Paul
Paul

Reputation: 1734

Android edittext get text on each line into an array with word wrap on?

I know you can split a string by text.split("\n") but this doesn't work with word wrap on. Any other way?

Upvotes: 0

Views: 2303

Answers (2)

Kevin Coppock
Kevin Coppock

Reputation: 134664

This can be done using the Layout API.

With comments:

public static List<CharSequence> getLines(TextView view) {
    final List<CharSequence> lines = new ArrayList<>();
    final Layout layout = view.getLayout();

    if (layout != null) {
        // Get the number of lines currently in the layout
        final int lineCount = layout.getLineCount();

        // Get the text from the layout.
        final CharSequence text = layout.getText();

        // Initialize a start index of 0, and iterate for all lines
        for (int i = 0, startIndex = 0; i < lineCount; i++) {
            // Get the end index of the current line (use getLineVisibleEnd()
            // instead if you don't want to include whitespace)
            final int endIndex = layout.getLineEnd(i);

            // Add the subSequence between the last start index
            // and the end index for the current line.
            lines.add(text.subSequence(startIndex, endIndex));

            // Update the start index, since the indices are relative
            // to the full text.
            startIndex = endIndex;
        }
    }
    return lines;
}

Without comments:

public static List<CharSequence> getLines(TextView view) {
    final List<CharSequence> lines = new ArrayList<>();
    final Layout layout = view.getLayout();

    if (layout != null) {
        final int lineCount = layout.getLineCount();
        final CharSequence text = layout.getText();

        for (int i = 0, startIndex = 0; i < lineCount; i++) {
            final int endIndex = layout.getLineEnd(i);
            lines.add(text.subSequence(startIndex, endIndex));
            startIndex = endIndex;
        }
    }
    return lines;
}

Upvotes: 7

Marcus Gabilheri
Marcus Gabilheri

Reputation: 1289

If you know how large/how many characters your edit text have you can split every X characters based on the size.

Upvotes: 0

Related Questions