我有一个带有以下构造函数的自定义 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()
方法,在其中提供初始化公共(public)信息三个构造函数
关于android - Paint 实例从未在自定义 ViewGroup 构造函数中初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26139733/