简体   繁体   中英

Center Align text in linear layout in eclipse?

I have a button on the left of the linear layout and a textview that I want to be in the center of the whole linear layout, but it ends up being pushed to the right by the button no matter what I try.

<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="@drawable/hed_bg" >

<Button
    android:id="@+id/button_back_memory"
    android:layout_width="60dp"
    android:layout_height="30dp"
    android:layout_marginLeft="5dp"
    android:layout_marginTop="10dp"
    android:background="@drawable/back_button"
    android:text="Back"
    android:textColor="#69adda"
    android:textSize="13sp" />

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:layout_weight="0.29"
    android:gravity="center"
    android:text="Memory"
    android:textColor="@android:color/white"
    android:textSize="15sp" />
</LinearLayout>

I need the text to be centered in the textview and the text view to be centered in the linear layout without being moved by the button.

You should use this attribute to make your TextView centered

android:layout_gravity="center"

and this to make your text centered in TextView

android:gravity="center"

Actually it is what LinearLayout does: packing its children after each other. If you don't want that behavior use another class, like FrameLayout.

Change your LinearLayout to a RelativeLayout,

Change your TextView replace android:layout_width="fill_parent" by android:layout_width="wrap_content"

and add android:layout_centerInParent="true"

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