Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextView - Splitting Lines

I have TextView in a FrameLayout. The Textview is aligned to the left bottom of the FrameLayout and has a specific MaxWidht.

It currently looks like this:

Lorem ipsum dolor sit amet, vel et

alia fierent forensibus.

What I want to achieve is this:

Lorem ipsum dolor

sit amet, vel et alia fierent forensibus.

So basically, the text should be splitted by the width of the bottom line, not by the top line.

Is there an easy way to achieve this?

Layout.xml

<FrameLayout
        android:id="@+id/flHeader"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="orem ipsum dolor sit amet, vel et alia fierent forensibus."
            android:id="@+id/txtHeader"
            android:layout_gravity="left|bottom"
            android:textColor="#ffffff"
            android:layout_below="@id/txtDescriptionShort"
            android:maxWidth="400dp" />

</FrameLayout>

Any help is very appreciated!

Thank you in advance.

like image 735
Al0x Avatar asked Jan 24 '26 19:01

Al0x


1 Answers

A quick and dirty solution could be the following function:

private String format(String s, int maxLength) {
    String s2 = s.substring(s.indexOf(' ', s.length() - maxLength) + 1);
    return s.substring(0, s.length()  -  s2.length()) + "\n" + s2;
}

used:

String s = "Lorem ipsum dolor sit amet, vel et alia fierent forensibus."
int tvMaxLength = 45;

txtHeader.setText(format(s, tvMaxLength));

It works of course only for two lines of text and is error prone.

A better candidate for a function that 'fills' lines of text 'bottom-up' could look something like that.

private String formatMultiline(String s, int maxLength) {

    if (s == null  || s.length() == 0) {
        return "";
    }

    if (maxLength < 1) {
        return s;
    }

    StringBuilder sb = new StringBuilder(s);
    int position = sb.length() - 1;
    while (position >=  maxLength - 1) {
        position = s.indexOf(' ', position - maxLength + 1);
        sb.setCharAt(position, '\n');
    }
    return sb.toString();
}

Please note that I have done only very basic testing. For example the function assumes that there are no double spaces in the string.

like image 57
Walt Avatar answered Jan 26 '26 09:01

Walt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!