简体   繁体   中英

Why isn't my view centering horizontally in my linear layout?

I've been trying to get the chronometer (child of textview) to center in this horizontal linear layout for a few hours. I've looked on here and saw everyone mentioning the gravity attribute. I changed this and experimented with other attributes to no success. Below is the XML from android studio. What am I doing wrong?

    <LinearLayout
    android:id="@+id/statusDisplay"
    android:layout_width="match_parent"
    android:layout_height="20dp"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/score"
        android:layout_width="wrap_content"
        android:layout_height="20dp"
        android:gravity="left"
        android:text="Score" />

    <Chronometer
        android:id="@+id/timer"
        android:layout_width="wrap_content"
        android:layout_height="20dp"
        android:gravity="center_vertical" />

</LinearLayout>

Can you try this?

<LinearLayout
     android:id="@+id/statusDisplay"
     android:layout_width="match_parent"
     android:layout_height="20dp"
     android:orientation="horizontal"
     android:gravity="center">

     <TextView
        android:id="@+id/score"
        android:layout_width="wrap_content"
        android:layout_height="20dp"
        android:text="Score" />

    <Chronometer
        android:id="@+id/timer"
        android:layout_width="wrap_content"
        android:layout_height="20dp" />
</LinearLayout>

Otherwise, You can use RelativeLayout

<RelativeLayout
    android:id="@+id/statusDisplay"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="20dp">

    <TextView
        android:id="@+id/score"
        android:layout_width="wrap_content"
        android:layout_height="20dp"
        android:text="Score"/>

    <Chronometer
        android:id="@+id/timer"
        android:layout_width="wrap_content"
        android:layout_height="20dp"
        android:layout_centerHorizontal="true"/>
</RelativeLayout>

Either use Gravity property in the parent layout. Or use a RelativeLayout as a parent instead and use attribute layout:center_Horizontal ="true" on the parent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM