我试图获取文字视图' 2' (黑色)出现在我的视图中心但由于某种原因它不会出现。有谁知道这里有什么问题以及如何解决这个错误?有没有办法以编程方式显示它并改变它的颜色而不是使用XML?
XML
<com.apptacularapps.car.RectangleTextView
android:layout_width="120dp"
android:layout_height="40dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:text="2"
android:gravity="center"
android:background="#808080"/>
爪哇
public class RectangleTextView extends View {
Paint paint;
private TextPaint mTextPaint;
public RectangleTextView(Context context) {
super(context);
init();
}
public RectangleTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public RectangleTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
paint = new Paint();
paint.setColor(Color.RED);
paint.setStrokeWidth(1); // convert to dp?
paint.setStyle(Paint.Style.STROKE); // delete line for filled rect
mTextPaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
mTextPaint.setTextAlign(Paint.Align.CENTER);
mTextPaint.setColor(Color.BLACK);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawText("2", 0, 0, paint);
paint.setTextSize(20);
int w = canvas.getWidth();
int h = canvas.getHeight();
int rectWidth = w/5;
int space = w/15;
int topRectHeight = getPaddingTop();
int bottomRectHeight = getPaddingBottom();
for (int i = 0; i < 4; i++) {
int left = i * (rectWidth + space);
int right = left + rectWidth;
Rect rect = new Rect(left, 0, right, topRectHeight);
canvas.drawRect(rect, paint);
Rect rect2 = new Rect(left, h - bottomRectHeight, right, h);
canvas.drawRect(rect2, paint);
}
}
}
答案 0 :(得分:1)
您没有定义文本绘制方式的绘图对象,也没有在onDraw()方法中调用canvas.drawText()。这样做:
private TextPaint mTextPaint;
private void init() {
mTextPaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
// You can tweak the appearance of the textpaint here
mTextPaint.setTextAlign(Align.CENTER);
mTextPaint.setColor(color);
}
@Override
public void onDraw() {
super.onDraw()
// You can tweak the positioning of the text here
canvas.drawText("2", 25, 25, mTextPaint);
}