Android XML: Centering Horizontally On Bottom
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:text="Title"
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30px"
android开发者_运维技巧:textStyle="bold"
>
</TextView>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="60px">
<Button
android:text="Choose a Story"
android:id="@+id/choose"
android:layout_width="150px"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginBottom="1px">
</Button>
<Button
android:text="Info"
android:id="@+id/info"
android:layout_width="150px"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginBottom="1px">
</Button>
</LinearLayout>
</LinearLayout>
In this code, as you can see, there is a title, 2 linear layouts, and 2 buttons that are inside a linear layout. What I'm trying to do is center the 2 buttons. No matter what I do, I can never get the 2 buttons to be centered at the bottom with a height of 60px.
In the end I'm trying to make the text centered both vertically and horizontally, and have the 2 buttons on the bottom centered horizontally. What do I need to change?
Heres a picture of what it looks like in the Layout Editor.
On your inner linear layout, set the layout_gravity
.
Here's one solution
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:text="Title"
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30dip"
android:textStyle="bold"
/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="60dip"
android:layout_gravity="bottom|center_horizontal"
android:layout_marginBottom="1dip"
>
<Button
android:text="Choose a Story"
android:id="@+id/choose"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
/>
<Button
android:text="Info"
android:id="@+id/info"
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="wrap_content"
/>
</LinearLayout>
</FrameLayout>
In general, you should style the outermost component (container) which will then position all of its children accordingly. As a side not, this layout would be achieved using just a single (or pair, depending on exactly what you're trying to do) or FrameLayout
s, which would significantly reduce the layout overhead. While there's nothing wrong with LinearLayout
, it is surprisingly computationally expensive.
精彩评论