gpt4 book ai didi

android - Paint 实例从未在自定义 ViewGroup 构造函数中初始化

转载 作者:搜寻专家 更新时间:2023-11-01 08:48:14 25 4
gpt4 key购买 nike

我有一个带有以下构造函数的自定义 ViewGroup:

public BoxGridLayout(Context context) {
super(context, null);
}

public BoxGridLayout(Context context, AttributeSet attrs) {
super(context, attrs, 0);
}

public BoxGridLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);

//Recupero gli attributi che ho creato nel file attrs.xml
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BoxGridLayout, 0, defStyle);

int strokeWidth = a.getDimensionPixelSize(R.styleable.BoxGridLayout_separatorWidth, 0);
int strokeColor = a.getColor(R.styleable.BoxGridLayout_separatorColor, Color.WHITE);

a.recycle();

mGridPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mGridPaint.setStyle(Paint.Style.STROKE);
mGridPaint.setColor(strokeColor);
mGridPaint.setStrokeWidth(strokeWidth);
}

在 dispatchDraw() 方法之后,我需要 mGridPaint 来创建一个网格:

@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);

for (int i = 0; i <= getWidth(); i += (getWidth() / COUNT)) {
canvas.drawLine(i, 0, i, getHeight(), mGridPaint);
}
for (int i = 0; i <= getHeight(); i += (getHeight() / COUNT)) {
canvas.drawLine(0, i, getWidth(), i, mGridPaint);
}
}

我在布局文件中使用了这个 ViewGroup,如下所示:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">


<com.example.customview.widget.BoxGridLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
app:separatorWidth="2dp">

....
....


</com.example.customview.widget.BoxGridLayout>


</FrameLayout>

问题:可悲的是我在 mGridPaint 上有一个 NullPointerException:

java.lang.NullPointerException: Attempt to read from field 'long android.graphics.Paint.mNativePaint' on a null object reference
at android.view.GLES20Canvas.drawLines(GLES20Canvas.java:862)
at android.view.GLES20Canvas.drawLine(GLES20Canvas.java:852)
at it.liqid.customview.widgets.BoxGridLayout.dispatchDraw(BoxGridLayout.java:94)
.....

如何解决这个错误?谢谢!

最佳答案

布局膨胀器调用的构造函数是public BoxGridLayout(Context context, AttributeSet attrs)。变化

public BoxGridLayout(Context context, AttributeSet attrs) {
super(context, attrs, 0);
}

public BoxGridLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}

或者在构造函数中用两个参数初始化画家

但请注意,自 API 级别 11 以来,带有 int defStyle 的构造函数可用。您还可以使用 public void init() 方法,在该方法中提供初始化通用给三个构造函数

关于android - Paint 实例从未在自定义 ViewGroup 构造函数中初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26139733/

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