Reputation: 1260
I try to use my own SurfaceView in XML and I am unable to do it. I get NullPointerException.
According internet it should look like this:
Activity:
package editor;
import android.app.Activity;
import android.os.Bundle;
import com.example.balls_menu_v1.R;
public class EditorActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editor);
EditorView ev = (EditorView) findViewById(R.id.editorView);
}
}
If I comment findViewById
I get NullPointerException.
SurfaceView:
package editor;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class EditorView extends SurfaceView {
public EditorView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void onFinishInflate() {
super.onFinishInflate();
SurfaceHolder holder = getHolder();
Canvas canvas = holder.lockCanvas();
canvas.drawColor(Color.GREEN);
holder.unlockCanvasAndPost(canvas);
}
}
Layout: editor.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<editor.EditorView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/editorView"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>
Upvotes: 2
Views: 7892
Reputation: 8028
you can't call Canvas canvas = holder.lockCanvas();`
before the oncreate flow finish,
you should call it after the oncreate finish
Upvotes: 0
Reputation: 1260
I found answer: implement SurfaceHolder.Callback
, add all 3 constructors of SurfaceView and add getHolder().addCallback(this);
to each constructor.
Code:
public class EditorView extends SurfaceView implements SurfaceHolder.Callback{
public EditorView(Context context) {
super(context);
getHolder().addCallback(this);
// TODO Auto-generated constructor stub
}
public EditorView(Context context, AttributeSet attrs) {
super(context, attrs);
getHolder().addCallback(this);
// TODO Auto-generated constructor stub
}
public EditorView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
getHolder().addCallback(this);
// TODO Auto-generated constructor stub
}
public void doDraw() {
SurfaceHolder holder = getHolder();
Canvas canvas = holder.lockCanvas();
canvas.drawColor(Color.GREEN);
holder.unlockCanvasAndPost(canvas);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {}
@Override
public void surfaceCreated(SurfaceHolder holder) {
doDraw();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}
Upvotes: 5