TextView和文本颜色的子类

问题描述:

我想实现一个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

你将有你的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

我认为你可以在得到颜色:

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

然后设置这个颜色textPaint。