You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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_marginRight to the left TextView or android:layout_marginLeft to the centered one to create spacing.
  • Always assign unique android:id values to each TextView for easy reference in your code.

内容的提问来源于stack exchange,提问作者HEMA RAMANA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 02:30:11