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

时间:2014-10-01 10:54:28

标签: android

我有一个带有以下构造函数的自定义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)
        .....

如何修复此错误? 谢谢!

1 个答案:

答案 0 :(得分:3)

布局inflater调用的构造函数是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()方法来提供三个构造函数的通用初始化