2011-03-26 37 views
1

我想實現一個TextView的子類,它可以打印垂直旋轉的文本,但是我遇到了麻煩,打印文本時我從XML佈局指定的顏色。類代碼是:TextView和文本顏色的子類

import android.content.Context; 
import android.graphics.Canvas; 
import android.graphics.Rect; 
import android.text.TextPaint; 
import android.util.AttributeSet; 
import android.widget.TextView; 

public class VerticalTextView extends TextView { 
    private Rect bounds = new Rect(); 
    private TextPaint textPaint; 

    public VerticalTextView(Context context) { 
     super(context); 
    } 

    public VerticalTextView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
    } 

    @Override 
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
     textPaint = getPaint(); 
     textPaint.getTextBounds((String) getText(), 0, getText().length(), bounds); 
     setMeasuredDimension((int) (bounds.height() + textPaint.descent()), bounds.width()); 
    } 

    @Override 
    protected void onDraw(Canvas canvas) { 
     canvas.rotate(-90, bounds.width(), 0); 
     canvas.drawText((String) getText(), 0, -bounds.width() + bounds.height(), textPaint); 
    } 
} 

我沒有必要爲此視圖定製屬性,所以我沒有聲明它的樣式。

我用我的活動這一觀點通過這種佈局:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 

    <com.verticaltextview.VerticalTextView 
     android:layout_width="wrap_content" android:layout_height="wrap_content" 
     android:text="Hello World" android:textColor="#ff0000ff" 
     android:textStyle="italic" /> 
</LinearLayout> 

正如你所看到的,我同時指定文本顏色(藍色)和文字樣式(斜體),但只樣式被應用,因爲文本以黑色打印。如果在onDraw()方法中,我通過textPaint.setColor(0xff00ff00)對顏色進行硬編碼,那麼文本將以正確的顏色打印。

對此提出建議?感謝;)

+0

嘗試RGB android:textColor =「#0000FF」,你不需要聲明alpha通道 – Blundell 2011-03-26 10:34:07

回答

1

你將有你的VerticalTextView的構造函數更改爲以下:

private int   col  = 0xFFFFFFFF; 

public VerticalTextView(Context context, AttributeSet attrs) 
{ 
    super(context, attrs); // was missing a parent 
    col = getCurrentTextColor(); 
} 

然後加入

textPaint.setColor(col); 

onDraw()功能。

希望這會有所幫助。

+0

他的構造函數將XML屬性設置爲超類將處理文本顏色xml屬性? – Blundell 2011-03-26 11:25:11

+0

你說得對,布倫德爾。我已經更正了我的答案,以更簡單的一個:) ...感謝您指出。 – rajath 2011-03-26 12:48:16

+0

謝謝,這工作,但爲什麼有必要像這樣設置油漆的顏色?不應該由「超級」構造函數自動完成嗎? – Venator85 2011-03-26 16:31:35

0

我認爲你可以在得到顏色:

**public VerticalTextView(Context context, AttributeSet attrs) { 
    super(context, attrs); 
}** 

然後設置這個顏色textPaint。