【问题标题】:Android align a text at the top center failsAndroid在顶部中心对齐文本失败
【发布时间】:2018-12-19 07:12:38
【问题描述】:

我尝试在顶部中心对齐文本但失败了

我已经检查了This question,但答案失败了

我试过了

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".OnboardingActivity">

<TextView
    android:layout_alignParentTop="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:text="Welcome"
    />

这是在未居中的模拟器上运行后得到的结果

【问题讨论】:

  • 请指定您想要达到的目标
  • @KevinKurien 我希望它水平居中但在顶部
  • @GEOFFREYMWANGI 比在您的TextView 中使用android:layout_centerInParent="true"android:layout_alignParentTop="true"

标签: android android-layout


【解决方案1】:

将此添加到您的RelativeLayout

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:text="Welcome"
        android:layout_centerHorizontal="true"/>

【讨论】:

    【解决方案2】:

    试试这个:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:gravity="center"
            android:text="Welcome" />
    
    </LinearLayout>
    

    【讨论】:

    • 我看到我忘了让宽度匹配父项
    • 我不知道谁投了反对票,但这是正确答案
    • @GEOFFREYMWANGI 是的,重力只适用于线性布局.. 相对布局有自己的标签
    【解决方案3】:

    只需在您的 TextView

    中使用 android:layout_centerInParent="true"

    试试这个

    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".OnboardingActivity">
    
    <TextView
        android:layout_alignParentTop="true"
        android:layout_width="wrap_content"
        android:layout_centerInParent="true"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Welcome"
        />
    
    </RelativeLayout>
    

    【讨论】:

    • 我希望它位于屏幕的顶部中心而不是中心
    • @GEOFFREYMWANGI 你能把你的预期输出分享为图片吗
    • @GEOFFREYMWANGI 并且它会将您的文本视图设置在屏幕顶部|中心位置检查我在TextView 中添加了android:layout_alignParentTop="true"android:layout_centerInParent="true"
    猜你喜欢
    • 1970-01-01
    • 2014-09-01
    • 2019-08-07
    • 1970-01-01
    • 2014-12-28
    • 1970-01-01
    • 2015-08-23
    • 2023-04-04
    • 1970-01-01
    相关资源
    最近更新 更多