Android:how To Change Attributes In Ondraw() By Onclicklistener
I have a simple ondraw() function. private class MyViewCircle extends View { public MyViewCircle(Context context) { super(context); // TODO Auto-gen
Solution 1:
you could set some variables to represent there attributes, for example, in your case,you can set a n int for the color, and three float for the coordinates of the center and the radius.
in your onClick() method, change the values of there variables , and then call invalidate() to redraw the image.
Solution 2:
You can use a member variable to store the state, change it onClick
, and check it in onDraw
.
To hook up the click event properly, make sure you call setOnClickListener
in your constructor, and call invalidate
in onClick
to force a redraw.
privateclassMyCircleextendsViewimplementsOnClickListener {
privatebooleanmDrawBlueCircle=false;
privatePaintmPaint=newPaint();
publicMyCircle(Context context) {
super(context);
setOnClickListener(this);
}
@OverrideprotectedvoidonDraw(Canvas canvas) {
floatx=20;
floaty=20;
floatr=50;
intcolor= Color.BLACK;
if (mDrawBlueCircle) {
x = 30;
y = 30;
color = Color.BLUE;
}
mPaint.setColor(color);
canvas.drawCircle(x, y, r, mPaint);
}
@OverridepublicvoidonClick(View v) {
mDrawBlueCircle = true;
invalidate();
}
}
Notice that I also store the Paint
in a member variable mPaint
. This prevents new objects to be created on each draw cycle and reduces garbage collection.
Post a Comment for "Android:how To Change Attributes In Ondraw() By Onclicklistener"