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)
why is this so? how can I fix it?
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.