Thursday, May 3, 2012

Layout technique: Center a TextView with a Button left and right


Layout technique: Center a TextView with a Button left and right
While working on an application which should look similar to an iPhone application, I have to create a bar at the top where I have a back and a forward button (each on one side) and a dynamic text centered in the middle between them.
To get this done, I searched quite a lot and got it finally to work.
The surrounding layout should be the RelativeLayout with two Buttons (in my case I used ImageViews) and a TextView.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="50dip"
    android:background="#666666"
    android:paddingTop="3dip">
    <ImageView android:id="@+id/buttonLeft"
        android:layout_width="50dip"
        android:layout_height="50dip"
        android:layout_alignParentLeft="true"
        android:paddingLeft="3dip"
        android:scaleType="centerInside"
        android:clickable="true"
        android:src="@drawable/buttonLeft"/>
    <TextView android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textColor="#000000"
        android:textSize="20dip"
        android:textStyle="bold"
        android:text="@string/titleText"/>
    <ImageView android:id="@+id/buttonRight"
        android:layout_width="50dip"
        android:layout_height="50dip"
        android:layout_alignParentRight="true"
        android:paddingRight="3dip"
        android:scaleType="centerInside"
        android:clickable="true"
        android:src="@drawable/buttonRight"/>
</RelativeLayout>
As you can see, there are some layout params the auto completion didn’t list at all.
The params layout_centerVertical / layout_centerHorizontal do what they are named for and layout_alignParentRight / layout_alignParentLeft are like the CSS float: left / right.
Last tipp: If you have an application with different activitys/layouts but with some repeating layout parts, like the bar at the top, try to use the Tag.

No comments: