5

In my example when I press a button, a shape is displayed but when I press another button the previous shape gets erased.I want the shape to persist when another button is pressed. I am using the method invalidate() after every shape is displayed. Can you please give me a solution?Below is the Activity i have used.

public class StartMyDrawView extends Activity{
    MyDrawView mydrawview;
    public static int action=0;
    Intent netIntent;
    LinearLayout draw ;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("StartMyDrawView", "OnCreate()");
        setContentView(R.layout.designgraphic);
        draw = (LinearLayout) findViewById(R.id.linearLayout1);
        Button btnLine=(Button) findViewById(R.id.button1);
        Button btnCircle=(Button) findViewById(R.id.button2);
        Button btnRectangle=(Button) findViewById(R.id.button4);
        Button btnText=(Button) findViewById(R.id.button5);

        btnLine.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                action=1;
                draw.invalidate();
            }
        });

        btnCircle.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                action=2;
                draw.invalidate();
            }
        });

       btnRectangle.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                action=3;
                draw.invalidate();
            }
        });

        btnText.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                action=4;
                draw.invalidate();
            }
        });

        mydrawview =new MyDrawView(this);
        draw.addView(mydrawview);
    }

}

and My class that extends View is as follows

public class MyDrawView extends View {

Paint paint = new Paint();
int actionVal=0;
public MyDrawView(Context context) {
    super(context);
}

public void onDraw(Canvas canvas)
{
    super.onDraw(canvas);
     paint.setColor(Color.RED);
     paint.setStyle(Paint.Style.STROKE);
     if(StartMyDrawView.action==1)
         canvas.drawLine(0, 0, 200, 200, paint);
     if(StartMyDrawView.action==2)
         canvas.drawCircle(150, 150, 50, paint);
     if(StartMyDrawView.action==3)
         canvas.drawRect(20, 20, 150, 150, paint);
     if(StartMyDrawView.action==4)
         canvas.drawText("JUST DEMO", 150, 150, paint);
}

}

AbhishekB
  • 2,111
  • 3
  • 18
  • 23

1 Answers1

0

I think the canvas is cleared each time onDraw is called.

One method of resolving the problem is to retain the state by doing your draw operations on a global Bitmap, and the onDraw would draw the Bitmap to the Canvas. This isn't much work, and for an example see the accepted answer here.

Android Developers topic on drawables here.

Community
  • 1
  • 1
BDFun
  • 531
  • 2
  • 7