当我单击一个按钮时,我试图使我的画布无效。我有一个带有按钮的布局,下面我有一个画布视图。当我点击一个按钮时,圆圈应该隐藏或显示。现在在代码中,我只能使我的画布失效一次。当我第一次按下按钮时,它起作用了。但是当我按第二次时它不起作用。示例:如果我按隐藏,则显示它有效。但是当我再次按下隐藏按钮时它不起作用。当我单击一个按钮时,我希望 CanvasView 每次都无效。不仅是第一次。
public class CanvasWithButtonsActivity extends Activity {
boolean showCircle = true;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layout());
findViewById(R.id.buttonHide).setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
//HIDE
showCircle = false;
//How do i invalidate my canvas from here?
CanvasView cv = new CanvasView(getApplicationContext());
cv.invalidate();
}
});
findViewById(R.id.buttonShow).setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
//SHOW
showCircle = true;
//How do i invalidate my canvas from here?
CanvasView cv = new CanvasView(getApplicationContext());
cv.invalidate();
}
});
}
public RelativeLayout layout(){
RelativeLayout mainLayout = new RelativeLayout(this);
mainLayout.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.FILL_PARENT, 1));
mainLayout.setBackgroundColor(Color.WHITE);
View buttonLayout = LayoutInflater.from(getBaseContext()).inflate(R.layout.main, null);
buttonLayout.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.FILL_PARENT, 1));
CanvasView cv = new CanvasView(getApplicationContext());
mainLayout.addView(cv);
mainLayout.addView(buttonLayout);
return mainLayout;
}
private class CanvasView extends View{
public CanvasView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
protected void onDraw(Canvas myCanvas){
Paint myPaint = new Paint();
myPaint.setColor(Color.BLUE);
if(showCircle == true)
myCanvas.drawCircle(myCanvas.getWidth()/2, 100, 20, myPaint);
}
}
}
如果有人对此问题有解决方案,它将解决我的许多问题。