Change canvas color onTouchEvent Android -
i'm trying make activity in canvas color changes when tap canvas.
with code have, error:
attempt invoke virtual method 'void android.graphics.canvas.drawrect(float, float, float, float, android.graphics.paint)' on null object reference
this part of activity code.
public class coloractivity extends activity { private float x = 0; private float y = 0; public canvas canvas; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_color); setcontentview(new myview(this)); } public class myview extends view { public myview(context context) { super(context); // todo auto-generated constructor stub setfocusableintouchmode(true); } @override protected void ondraw(canvas canvas) { super.ondraw(canvas); int x = getwidth(); int y = getheight(); paint paintcanvas = new paint(); paintcanvas.setstyle(paint.style.fill); paintcanvas.setcolor(color.white); paintcanvas.setcolor(color.parsecolor("#f44336")); canvas.drawrect(0, 0, x, y, paintcanvas); } public boolean ontouchevent(motionevent event) { switch (event.getaction()) { case motionevent.action_down: paint repaintcanvas = new paint(); repaintcanvas.setstyle(paint.style.fill); repaintcanvas.setcolor(color.white); repaintcanvas.setcolor(color.parsecolor("#2196f3")); canvas.drawrect(0, 0, 100, 100, repaintcanvas); invalidate(); break; case motionevent.action_move: log.d("log","move"); invalidate(); break; case motionevent.action_up: log.d("log", "up"); invalidate(); break; } return super.ontouchevent(event); } }
what doing wrong?
i think know problem. invalidate calls again ondraw() method , overwrites whatever paint in ontouchevent method.
try following code:
public class coloractivity extends activity { private float x = 0; private float y = 0; public canvas canvas; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_color); setcontentview(new myview(this)); } public class myview extends view { paint paintcanvas; public myview(context context) { super(context); paintcanvas = new paint(); paintcanvas.setstyle(paint.style.fill); paintcanvas.setcolor(color.white); paintcanvas.setcolor(color.parsecolor("#f44336")); // todo auto-generated constructor stub setfocusableintouchmode(true); } @override protected void ondraw(canvas canvas) { super.ondraw(canvas); int x = getwidth(); int y = getheight(); canvas.drawrect(0, 0, x, y, paintcanvas); } public boolean ontouchevent(motionevent event) { switch (event.getaction()) { case motionevent.action_down: paintcanvas.setstyle(paint.style.fill); paintcanvas.setcolor(color.white); paintcanvas.setcolor(color.parsecolor("#2196f3")); invalidate(); break; case motionevent.action_move: log.d("log","move"); invalidate(); break; case motionevent.action_up: log.d("log", "up"); invalidate(); break; } return super.ontouchevent(event); } }
Comments
Post a Comment