4

I have a problem, that is maybe silly, but I just can't figure out why this is not working.

Basically, I have a header in my activity. This header should be centered.

Layout-XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

<TextView 
    style="@style/TextHeader"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/define"
    />
</LinearLayout>

Definition in styles.xml

<style name="TextHeader">
    <item name="android:textSize">20dp</item>
    <item name="android:paddingTop">15dp</item>
    <item name="android:layout_gravity">center</item>
    <item name="android:paddingBottom">15dp</item>
</style>

As I understand, layout_gravity defines the gravity of the component itself, while gravity defines the gravity of the content of this component. I tried both ways, both with center and center_horizontal. I also made the header TextView layout_width:wrap_content and tried to center it with layout_gravity, but the result is always following (same thing if I put the app on my phone)

enter image description here

why is this so? how can I fix it?

Krushna Chulet
  • 1,625
  • 1
  • 10
  • 9
Valentino Ru
  • 4,964
  • 12
  • 43
  • 78
  • haven't you tried center_vertical? You could also use relativelayout instead of linear layout. – Mohit Aug 27 '12 at 20:44

4 Answers4

8

There are a few different solutions, this is one:

<TextView
    android:id="@+id/text"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:text="@string/define" />

This is another:

<RelativeLayout .../>

    <TextView
        ...
        android:centerInParent="true" />

</RelativeLayout>

You can adjust your style properties to whichever method you choose.

Sam
  • 86,580
  • 20
  • 181
  • 179
1
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:orientation="vertical" >

android:gravity - centers all views in parent (use it in layout)

android:layout_gravity - centers your view in parent (use it inside all views you want to center)

0

Try to use "center_horizontal" and layout_width:"fill_parent".

pawegio
  • 1,722
  • 3
  • 17
  • 29
0

Try

 center_vertical

or

 Use Relative Layout.
Mohit
  • 2,940
  • 2
  • 24
  • 32