gpt4 book ai didi

java - TextView 未出现在 onDraw 对象中

转载 作者:行者123 更新时间:2023-11-30 01:57:30 24 4
gpt4 key购买 nike

我试图让 TextView “2”(黑色)出现在我的 View 中心,但由于某种原因它不会出现。有谁知道这里出了什么问题以及如何解决此错误?有没有办法以编程方式而不是使用 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"/>

Java

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);
}
}
}

enter image description here

最佳答案

您没有定义文本绘制方式的绘画对象,也没有在 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);
}

关于java - TextView 未出现在 onDraw 对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31997135/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com