0

I'm developing an Android application, I have to implement a function that allow me to draw different points with canvas.

I have realized this function that works:

public class MainActivity extends AppCompatActivity {
    public Paint paint;
    public List<Point> coords;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new DrawingView(this));

        paint = new Paint();
        coords = new ArrayList();

        ImageView iv = new ImageView(getApplicationContext());
        iv.setImageResource(R.drawable.car);
        iv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT);
        iv.setLayoutParams(parms);
    }

    class DrawingView extends SurfaceView {

        private final SurfaceHolder surfaceHolder;
        private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);

        public DrawingView(Context context) {
            super(context);
            surfaceHolder = getHolder();
            paint.setColor(Color.BLACK);
            paint.setStyle(Paint.Style.FILL);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if(event.getAction() == MotionEvent.ACTION_DOWN) {
              addpoint(event.getX(), event.getY());
            }
            return false;
        }

        public void addpoint(float x, float y){

            Point point = new Point();
            point.x = Math.round(x);
            point.y = Math.round(y);
            coords.add(point);

            for(int i = 0; i< coords.size(); i++) {
                Canvas canvas = surfaceHolder.lockCanvas();
                canvas.drawColor(Color.WHITE);
                canvas.drawCircle(coords.get(i).x, coords.get(i).y, 20, paint);
                surfaceHolder.unlockCanvasAndPost(canvas);
            }
        }
    }
}

I have a problem, when i rotate my device the orientation change, and all points drawed disappear.

How i can keep all points ?

  • You may want to move some of the code that is in `onCreate` to `onStart`. – Al Lelopath Oct 20 '16 at 14:51
  • @AlLelopath What i must move in onStart ? –  Oct 20 '16 at 14:55
  • I'm not saying you "must", but rather that it's something you should look into. When you start the application it calls onCreate() and onStart(), whereas when you rotate the device onStart() is called, not onCreate(), so there may be code that needs to be moved from onCreate() to onStart(). – Al Lelopath Oct 20 '16 at 14:57

0 Answers0