AndroidEnthusiast
AndroidEnthusiast

Reputation: 6657

Text not centred in TextView on Android when using Gravity CENTER

I'm trying to achieve a simple initial, centred in a textview.

Here's my xml and the image it results in:

     <TextView
        android:id="@+id/initial_view"
        style="@style/my_style"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:background="@color/black"
        android:gravity="center"
        android:textAllCaps="true"
        android:text="C"
        android:textColor="@color/font_white"
        android:textSize="34sp" />

Gravity set to center. I also tried setting the gravity programatically.

Text not centered, textview

Am I missing something or is this an android bug?

Style is:

<style name="normal_text">
    <item name="android:typeface">monospace</item>
</style>

Upvotes: 2

Views: 689

Answers (3)

Ranjithkumar
Ranjithkumar

Reputation: 18356

try this,

android:textAlignment="gravity"

and also try this,

android:includeFontPadding="false"

Upvotes: 1

Frank D.
Frank D.

Reputation: 1306

Try this:

Create an XML file circle.xml in your drawable folder:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
    <solid android:color="@color/black" ></solid>
</shape>

and for your TextView:

<TextView
        android:id="@+id/initial_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/white"
        android:gravity="center"
        android:background="@drawable/circle"
        android:textSize="34sp"
        android:text="C" />

Upvotes: 0

NoChinDeluxe
NoChinDeluxe

Reputation: 3444

For android:gravity="center" to work your android:layout_width and android:layout_height need to be set to match_parent or fill_parent.

Upvotes: 0

Related Questions