Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: layout_gravity center does not center

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?

like image 376
Valentino Ru Avatar asked Jan 16 '23 17:01

Valentino Ru


2 Answers

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.

like image 131
Sam Avatar answered Jan 23 '23 09:01

Sam


<?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)

like image 28
Victor Pozdnyakov Avatar answered Jan 23 '23 09:01

Victor Pozdnyakov