在我的例子中,当我按下按钮时,会显示一个形状,但是当我按下另一个按钮时,前一个形状会被删除。我希望在按下另一个按钮时该形状仍然存在。在显示每个形状后,我使用方法invalidate()
。你能给我一个解决方案吗?下面是我用过的活动。
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);
}
}
和我扩展View的类如下
公共类MyDrawView扩展了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);
}
}