Is there a way to perfectly center the text?

I wanted to know if it is possible to create a custom TextView that perfectly centers the text, no matter what font. This is my main problem right now, but I'm also wondering if it is possible to set a specific height using pixels so that the height is also consistent. Comparing text fonts This figure shows how different fonts are sized and centered. The longest black line in the image is the middle part of the space. The letters in the picture are the same in all respects except the fonts. The text size is the same ( text.setTextSize(TypedValue.COMPLEX_UNIT_PX, 450); ), and they are all centered. Hope someone knows the answer to these questions! If you need any code from my application, just ask. Thanks!

EDIT: I know android:gravity="veritcal_center" , but this only works to a certain extent. What you see above is implemented in textview , but each font has a different center of gravity, so android:gravity="veritcal_center" does not really make all of these centers perfect on the screen. I am looking for a way to create a custom textview that somehow measures the height of the text and centers it with these parameters. The @vmironov clause in the comments works, but only if the textview has one character. I was not able to mess around with my code, but I will when I get a chance and I will send it here if I find anything. Thanks!

+6
source share
3 answers

An easy way to achieve what you want is to use the 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 of LinearLayout fixed if you want the text to be centered within a constant height and width

+2
source

Set the gravity value to "center_vertical". Sort of:

 android:gravity="center_vertical" 
0
source

You should be able to center your text by applying the gravity attribute to the contained TextView.

In XML, you must assign a TextView attribute that looks like this:

 <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:textSize="18sp" android:textAppearance="?android:attr/textAppearanceMedium" android:text="@string/some_text" /> 

If you want to specify a specific text size, it is strongly recommended that you use SP (scale pixels) as the unit of measurement, not pixels. You can also set the Appearance attribute for your TextView to control the size, which is also shown in the sample code.

-1
source

All Articles