1

I need to create navigation bar (which I include in many activities.xml) with background which has TextView at center with titlw and back button (sometimes Back button is visible sometimes is not). How to to center TextView to be always in center of Layout ? At the moment when Back is visible TextView is moved slightly to right.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center_vertical"
    android:background="@drawable/header_background"
    android:gravity="center_vertical"
    android:orientation="horizontal" >

    <Button
        android:id="@+id/btnPrevious"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/selector_previous_arrow"
        android:visibility="gone" />

    <TextView
        android:id="@+id/title"
        style="@style/title"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center_vertical|center_horizontal"
        android:gravity="center_vertical|center_horizontal"
        android:text="Title" />

</LinearLayout>
4

2 回答 2

5

RelativeLayout 将更好地满足您的需求:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/header_background" >

    <Button
        android:id="@+id/btnPrevious"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:paddingLeft="5dp"
        android:background="@drawable/selector_previous_arrow"
        android:visibility="gone" />

    <TextView
        android:id="@+id/title"
        style="@style/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Title" />

</RelativeLayout>

仅当宽度和高度设置为 时,属性layout_centerInParent才会起作用wrap_content。或者,您可以将高度和宽度设置为fill_parent并设置 TextView 的android:gravity="center".

为什么您的原始布局不起作用:

LinearLayout 不允许视图重叠。因此,即使您将 TextView 的高度和宽度设置为 fill_parent,它实际上也只会填充放置后退按钮后剩余的空间。因此,当按钮不可见时,TextView 居中。当按钮可见时,TextView 在剩余空间中居中:因此向右移动了一点。

编辑:更正(替换android:layout_alignLeft="true"android:layout_alignParentLeft="true"

于 2013-09-13T16:59:18.613 回答
0
<TextView
    android:id="@+id/title"
    style="@style/title"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:text="Title" />
于 2013-09-13T17:56:20.320 回答