Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to perfectly center text?

I wanted to know if it was possible to create a custom TextView that centers text perfectly, no matter what the font is. That's my major issue right now, but I'm also wondering if it's possible to set the specific height using pixels so that the height would also be consistent. Comparing text fonts This picture shows how different fonts are sized and centered. The longest black line in the picture is the middle of the white space. Letters in the picture are the same in every way except for the fonts. The text size is the same (text.setTextSize(TypedValue.COMPLEX_UNIT_PX, 450);), and they're all centered. I hope someone knows the answer to these questions! If you need any code from my app, just ask. Thanks!

EDIT: I am aware of android:gravity="veritcal_center", but that only works to an extent. What you see above is that implemented in the textview, but each font has a different center of gravity, so android:gravity="veritcal_center" wouldn't really make all of these center perfectly along the screen. I'm looking for a way to create a custom textView that somehow measures the height of text and centers it with those parameters. A suggestion by @vmironov in the comments works, but only if the textview has one character. I have not been able to mess around with his code, but I will when I get a chance and I'll post here if I find anything. Thanks!

like image 481
TheWizKid95 Avatar asked Jan 09 '13 00:01

TheWizKid95


1 Answers

A simple way to achieve what you want is to use following code:

<LinearLayout 
        android:layout_width="100dp"
        android:layout_height="20dp"
        android:gravity="center">

        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="18sp"
                android:text="@string/your_text" />
</LinearLayout>

set the height and width values of LinearLayout fixed if you want to set the text to be alligned in center within constant height and width

like image 194
Salman Zaidi Avatar answered Oct 23 '22 17:10

Salman Zaidi