2012-10-29 55 views
4

我有垂直排列的幾個完全相同的TextView S(同緣離開,同樣填充左,相同位置的左側)。它們可以具有不同的文本大小,以及文本可以以不同的字母開頭。問題在於,儘管TextView與左邊對齊,但其中的文本不是。是否有可能實現這一目標?在每個首字母前刪除/分解多餘的空格?或者我應該尋找一些特定的字體?下面刪除多餘的空間,因此可以適當左對齊

圖片顯示的情況。有三個TextView與左邊對齊,但每個字母從不同的點開始。 小號具有相同的尺寸,但不對齊。 i相當小,差距更大。

我所看到的:
Actual

我想要什麼:
Expected result (manually aligned)

代碼的例子:

<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> 
+0

的代碼粘貼,你試過嗎? – RajeshVijayakumar

+0

我不認爲這可能與一個TextView。你可能會使用畫布自己繪製文本,使用來自'Paint.getTextWidths()'的信息,但我不知道從那裏返回的寬度是否包含周圍的空白(我的猜測是它贏了)幫助)。 – Tim

+0

我確實認爲TextView可以實現,它只需要一個MonoSpaced字體。 – Machinarius

回答

0

雖然這個問題是舊的,我只是碰到了來了同樣的問題,並找到了如下解決方案,也許它可以幫助別人:

創建一個TextView子類,並覆蓋它的onDraw()方法如下:

// 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); 
} 

買者:雖然我已經觀察到的文本範圍爲具有對應於空像素的量的第一個字母前的左值,並且是符合的Paint#getTextBounds()其中指出它返回的文檔

,在(0,0)包圍的所有字符,有一個隱含的原點的最小矩形,

從而左邊的值是實際文本開始的地方,此修復程序可能不適合所有字體或配置工作。

還應當指出的是,這是左對齊單行文本一個簡單的解決方案;多行或滾動文字將需要進一步調整,或者可能無法使用此功能。

+0

感謝您的提交。首先檢查您的解決方案,並更新答案的狀態。 – BloodyStupidViktor

相關問題