Remove the extra space in front of the first letter of the text so that it can be correctly aligned to the left

I have several exact TextView aligned vertically (same edge on the left, same indent on the left, same position on the left). They may have different text sizes, and the text may begin with another letter. The problem is that although the TextView left-aligned, the text is missing from them. Can this be achieved? To remove / increase the extra space before each first letter? Or should I look for a specific font?

The figures below show the situation. There are three TextView aligned to the left, but each letter starts at a different point. s and m are the same size but not aligned. I am much smaller, and the gap is much larger.

What I see:
Actual

What I want:
Expected result (manually aligned)

Example code:

 <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="m" android:textColor="#88FF0000" android:textSize="250dp" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="s" android:textColor="#8800FF00" android:textSize="250dp" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="220dp" android:text="i" android:textColor="#880000FF" android:textSize="25dp" /> </RelativeLayout> 
+4
source share
1 answer

Although this question is old, I just ran into one problem and found a solution as follows: maybe it can help someone else:

Subclass TextView and redefine it onDraw() as follows:

 // bounds field to avoid allocations in onDraw() Rect bounds = new Rect(); @Override protected void onDraw(Canvas canvas) { getPaint().getTextBounds(getText().toString(), 0, getText().length(), bounds); canvas.translate(-bounds.left, 0); super.onDraw(canvas); } 

Caveat . Although I observed that the borders of the text have a left value corresponding to the number of empty pixels before the first letter, and corresponds to the documentation Paint#getTextBounds() , which states: what it returns

the smallest rectangle that spans all characters, with an implied beginning at (0,0),

thus, the left value is where the actual text begins; this hotfix may not work for all fonts or configurations.

It should also be noted that this is a simple solution for text with single-line left justification; multiline or scrolled text will need additional adjustments or may not work with it at all.

0
source

Source: https://habr.com/ru/post/1442809/


All Articles