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)
对颜色进行硬编码,那么文本将以正确的颜色打印。
对此提出建议?感谢;)
答
你将有你的VerticalTextView
的构造函数更改为以下:
private int col = 0xFFFFFFFF;
public VerticalTextView(Context context, AttributeSet attrs)
{
super(context, attrs); // was missing a parent
col = getCurrentTextColor();
}
然后加入
textPaint.setColor(col);
您onDraw()
功能。
希望这会有所帮助。
答
我认为你可以在得到颜色:
**public VerticalTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}**
然后设置这个颜色textPaint。
尝试RGB android:textColor =“#0000FF”,你不需要声明alpha通道 – Blundell 2011-03-26 10:34:07