我想實現一個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)
對顏色進行硬編碼,那麼文本將以正確的顏色打印。
對此提出建議?感謝;)
嘗試RGB android:textColor =「#0000FF」,你不需要聲明alpha通道 – Blundell 2011-03-26 10:34:07