问题
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.)
回答1:
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 -->
/>
回答2:
You can achieve this easily with a ConstraintLayout nowadays.
回答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>
来源:https://stackoverflow.com/questions/26306667/how-do-i-alignbaseline-to-bottom-line-of-multi-line-textview