13

I have two TextViews side by side. Let's say the left TextView is 1 line and the right TextView is 2 lines. Is there any way to align the baselines of the left TextView with the last line in the right TextView?

I'm open to using whatever layout (RelativeLayout, LinearLayout, etc.) that can accomplish this.

(The default behavior of android:layout_alignBaseline in Android is that it aligns the baselines of the top lines.)

Gus
  • 2,531
  • 4
  • 22
  • 28

2 Answers2

7

You could accomplish this with RelativeLayout if you implement a custom TextView. Specifically, you could override TextView.getBaseline like so:

package mypackage.name;

// TODO: imports, etc.

public class BaselineLastLineTextView extends TextView {
    // TODO: constructors, etc.

    @Override
    public int getBaseline() {
        Layout layout = getLayout();
        if (layout == null) {
            return super.getBaseline();
        }
        int baselineOffset = super.getBaseline() - layout.getLineBaseline(0);
        return baselineOffset + layout.getLineBaseline(layout.getLineCount()-1);
    }
}

Then you would use your custom TextView inside a RelativeLayout as follows:

<mypackage.name.BaselineLastLineTextView
    android:id="@+id/text_view_1"
    <!-- TODO: other TextView properties -->
/>

<TextView
    android:id="@+id/text_view_2"
    android:layout_alignBaseline="@id/text_view_1"
    <!-- TODO: other TextView properties -->
/>
pscuderi
  • 1,554
  • 12
  • 14
  • It's pretty burdensome to have to create a custom TextView, but this is definitely a smart solution. Thanks. I didn't try it out, but seems like it'll work. – Gus Oct 19 '16 at 00:50
-3

I guess a RelativeLayout would do it.

<RelativeLayout..>
    <TextView android:id="@+id/tv2"
        android:layout_alignParentRight="true"
        android:maxLines="2"
        ... />
    <TextView android:id="@+id/tv1"
        android:layout_toLeftOf="@id/tv2"
        android:layout_alignBottom="@id/tv2"
        android:maxLines="1"
        ... />
</RelativeLayout>  
An SO User
  • 24,612
  • 35
  • 133
  • 221