Subclass of TextView and text color
I'm trying to implement a subclass of TextView that prints the text vertically rotated, but I'm having troubles printing the text in the color I specify from an XML layout. The class code is:
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);
}
}
I have no need of custom properties for this view, so I'm not declaring a styleable for it.
I'm using this view in my activity by this layout:
<?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>
As you can see, I'm spe开发者_开发百科cifying both the text color (blue) and the text style (italic), but only the style is applied, as the text is printed in black. If in the onDraw()
method I hardcode a color by doing textPaint.setColor(0xff00ff00)
, then the text is correctly printed in color.
Suggestions? Thanks ;)
You will have to change the constructors of your VerticalTextView
to the following:
private int col = 0xFFFFFFFF;
public VerticalTextView(Context context, AttributeSet attrs)
{
super(context, attrs); // was missing a parent
col = getCurrentTextColor();
}
Then add
textPaint.setColor(col);
to your onDraw()
function.
Hope this helps.
i think you can get color in:
**public VerticalTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}**
then set this color to textPaint.
精彩评论