【问题标题】:Horizontally center two TextView with RelativeLayout使用RelativeLayout水平居中两个TextView
【发布时间】:2022-01-19 15:54:36
【问题描述】:

问题:

我试图将这两个 TextView 水平居中,但似乎找不到解决方案。

    <TextView
    android:id="@+id/have_account_tv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/register_btn"
    android:layout_marginTop="15dp"
    android:text="Already have an account? "
    android:textColor="@color/black" />

<TextView
    android:id="@+id/login_now_tv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textFontWeight="700"
    android:textColor="@color/main_blue"
    android:layout_below="@+id/register_btn"
    android:layout_marginTop="15dp"
    android:layout_toRightOf="@+id/have_account_tv"
    android:text="Log in now" />

解决方案

我已经使用 LinearLayout 包装两个 TextView 解决了这个问题,然后设置 centerHorizo​​ntal="true"。

<LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="15dp"
        android:layout_below="@+id/login_btn">
    <TextView
        android:id="@+id/havent_register_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Haven't Registered? "
        android:textColor="@color/black" />

    <TextView
        android:id="@+id/login_now_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textFontWeight="700"
        android:textColor="@color/main_blue"
        android:layout_alignBottom="@+id/havent_register_tv"
        android:layout_toRightOf="@+id/havent_register_tv"
        android:text="Register Here"/>
</LinearLayout>

【问题讨论】:

    标签: android xml textview android-relativelayout


    【解决方案1】:

    尝试将以下属性添加到 TextView XMLs

    android:layout_centerHorizontal="true"
    

    【讨论】:

    • 试过了。将 centerHorizo​​ntal=true 应用于其中一个将导致一个文本视图水平居中,同时将另一个文本视图推到一边。两者都申请也没有用。
    • @AhChing11 我误解了你的问题。你想要这些视图并排吗?因为它们都有`android:layout_below="@+id/register_btn"`。所以它们都不能水平居中,否则它们会相互重叠
    • 哇,那我该怎么办?
    • 这里有很多选项,你可以只用一个TextView,然后使用spans来改变中间文本的颜色。或者您可以在两者之间添加一个LinearLayout 并使用权重系统将它们划分为 50/50。更好的是你选择ConstraintLayout,它类似于RelativeLayout,但更强大。 @AhChing11
    • 啊,好吧,我想我会选择使用 LinearLayout,谢谢。
    猜你喜欢
    • 1970-01-01
    • 2014-05-22
    • 2016-07-18
    • 1970-01-01
    • 2014-12-18
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    • 2019-12-02
    相关资源
    最近更新 更多