Android中如何布局两个TextView:一个居左,一个居中?
Arrange Two TextViews in RelativeLayout (Left and Center)
To place one TextView on the left side of the screen and the other centered horizontally using RelativeLayout, you’ll use two core layout attributes to position each view precisely:
Key Positioning Attributes:
- For the left-aligned TextView: Use
android:layout_alignParentLeft="true"to anchor it directly to the left edge of the parent layout. - For the centered TextView: Use
android:layout_centerHorizontal="true"to center it horizontally within the parent’s bounds.
Complete Layout Code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/header_layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/white"> <!-- Left-aligned TextView --> <TextView android:id="@+id/tv_left" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:padding="8dp" android:text="Left-Aligned Text" /> <!-- Centered TextView --> <TextView android:id="@+id/tv_center" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:padding="8dp" android:text="Centered Text" /> </RelativeLayout>
Quick Notes:
- If long text causes overlap between the two views, add
android:layout_marginRightto the left TextView orandroid:layout_marginLeftto the centered one to create spacing. - Always assign unique
android:idvalues to each TextView for easy reference in your code.
内容的提问来源于stack exchange,提问作者HEMA RAMANA
相关产品推荐
相关产品推荐

