在LinearLayout中垂直居中放置TextView

时间:2018-08-09 10:56:09

标签: android android-linearlayout center vertical-alignment

我正在尝试将TextView放在LinearLayout中居中,并且将其水平居中而不是垂直居中。

下面是我的代码

<LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/taque"
                android:layout_width="fill_parent"
                android:layout_height="match_parent"
                android:layout_gravity="center"
                android:layout_marginLeft="7dp"
                android:layout_marginRight="7dp"
                android:layout_marginTop="3dp"
                android:gravity="center"
                android:text="Question"
                android:textColor="@color/Black"
                android:textSize="16dp"
                android:typeface="normal" />
        </LinearLayout>

4 个答案:

答案 0 :(得分:1)

尝试一下!

<LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center_horizontal"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/taque"
                android:layout_width="fill_parent"
                android:layout_height="match_parent"
                android:layout_gravity="center"
                android:layout_marginLeft="7dp"
                android:layout_marginRight="7dp"
                android:layout_marginTop="3dp"
                android:gravity="center"
                android:text="Question"
                android:textColor="@color/Black"
                android:textSize="16dp"
                android:typeface="normal" />
        </LinearLayout>

答案 1 :(得分:1)

您需要的是android:gravity="center"的TextView:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/taque"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="7dp"
        android:layout_marginRight="7dp"
        android:layout_marginTop="3dp"
        android:gravity="center"
        android:text="Question"
        android:textColor="@color/Black"
        android:textSize="16dp"
        android:typeface="normal" />
</LinearLayout>

答案 2 :(得分:1)

除了textview的宽度和高度,您的布局看起来还不错。 只需将textview的宽度和高度从 match_parent 更改为 wrap_content

<TextView
   android:id="@+id/taque"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"

答案 3 :(得分:1)

只需将android:gravity=“center“添加到您的TextView和LinearLayout中即可。