I will try to formulate a normal question. I have a simple application, but for this question I have simplified everything more to focus on the root of the problem. The essence of the application is a part of the screen, in my case it is SurfaceView
, where dynamically after each button click a geometric shape should appear and with each click should be more. I did this, but I had a problem. I have already cut as much as possible everything I could in the functional, in order to understand where the bug is and still do not understand why I have three such SurfaceView
(and it’s not even clear to me why three), which in turn, after pressing the button, change, although I should only have one SurfaceView
. This leads to the fact that I have three different sets of shapes that are filled in turn, instead of one. The first SurfaceView
is created in green: mCanvas.drawColor(Color.GREEN);
. Further, I don’t know why, after clicking the button, I SurfaceView
another SurfaceView
that I understand and the screen goes black. After the new click is the same (the third SurfaceView
), the fourth click again returns to green and again through the cycle. I understand perfectly well that the problem is in two lines in the listener for the button (marked with a comment), but I just can not understand what the error is ...
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); hideActionBar(); initView(); mSurfaceView.getHolder().addCallback(new SurfaceHolder.Callback() { @Override public void surfaceCreated(SurfaceHolder holder) { mCanvas = null; mSurfaceHolder = null; mSurfaceHolder = mSurfaceView.getHolder(); mCanvas = mSurfaceHolder.lockCanvas(); mCanvas.drawColor(Color.GREEN); mSurfaceHolder.unlockCanvasAndPost(mCanvas); } @Override public void surfaceDestroyed(SurfaceHolder holder) { } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } }); mRectangleButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Проблема тут! mCanvas = mSurfaceHolder.lockCanvas(); // drawRectangle(); mSurfaceHolder.unlockCanvasAndPost(mCanvas); } }); } }