如何让两个 TextView 在 RelativeLayout 中水平居中显示

本文探讨了一种方法,通过在RelativeLayout中设置一个空的占位View并调整TextView的margin,来实现两个TextView的水平居中显示。这种方法避免了使用LinearLayout。作者鼓励读者分享更多解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

stormzhang 的博客有一篇Tencent Interview , 其中有个问题是:如何让两个 TextView 在 RelativeLayout 中水平居中显示。我的第一反应是用一个 LinearLayout 包装它们。今天我想了另一种方法:

  • 在水平中心放置一个占位 view,内容为空
  • 在占位 view 的两侧各放置一个 view,并设置它们与占位 view 的 margin
为了显示更加清楚,我给 占位 view 和两侧的 view 都设置了背景,具体使用时可以去掉。布局文件如下:


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toLeftOf="@id/center"
        android:layout_marginRight="10dp"
        android:textSize="30sp"
        android:text="name"
        android:background="@android:color/holo_green_light"
        />

    <TextView
        android:id="@+id/center"
        android:layout_width="1dp"
        android:layout_height="20dp"
        android:layout_centerInParent="true"
        android:background="@android:color/holo_red_light"
        />

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@id/center"
        android:layout_marginLeft="10dp"
        android:text="title"
        android:textSize="30sp"
        android:background="@android:color/holo_green_light"
        />

</RelativeLayout> 


效果如下:



欢迎你提出更好的办法!

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值