java - Static Methods in Android -
im try create drawing app. in main activity have xml file contains drawing viewview
<app.color.drawingview android:layout_width="match_parent" android:layout_height="200dp" android:id="@+id/drawing" android:layout_marginleft="5dp" android:layout_marginright="5dp" android:background="#ffffffff" android:layout_above="@+id/settings" android:layout_alignparenttop="true" />
this based on drawing view class:
package app.color; import android.content.context; import android.graphics.canvas; import android.graphics.color; import android.graphics.paint; import android.graphics.path; import android.util.attributeset; import android.view.motionevent; import android.view.view; public class drawingview extends view { private paint paint = new paint(); private path path = new path(); public drawingview(context context, attributeset attrs) { super(context, attrs); paint.setantialias(true); paint.setstrokewidth(5f); paint.setcolor(color.black); paint.setstyle(paint.style.stroke); paint.setstrokejoin(paint.join.round); } @override protected void ondraw(canvas canvas) { canvas.drawpath(path, paint); } @override public boolean ontouchevent(motionevent event) { // coordinates of touch event. float eventx = event.getx(); float eventy = event.gety(); switch (event.getaction()) { case motionevent.action_down: // set new starting point path.moveto(eventx, return true; case motionevent.action_move: // connect points path.lineto(eventx, eventy); break; default: return false; } // makes our view repaint , call ondraw invalidate(); return true; } public void setcolor(string newcolor){ invalidate(); int paintcolor = color.parsecolor(newcolor); paint.setcolor(paintcolor); } }
then in activity on button click have method which want able call setcolor method in drawingview change color. wont let me because "non-static method cannot referenced static context"
public void toblack(view view) { drawingview.setcolor("#00000"); intent intent = new intent(colors.this, mainactivity.class); startactivity(intent); }
create instance of drawingview.
thats ,
drawingview drawingview = new drawingview(); drawingview.setcolor("#00000");
setcolor
instance method, meaning need instance of drawingview
class in order call it. you're attempting call on drawingview
type itself.
just make code to
drawingview dv = new drawingview(); dv.setcolor("#00000"); intent intent = new intent(colors.this, mainactivity.class); startactivity(intent);
for example have
public drawingview(context context, attributeset attrs) { super(context, attrs); paint.setantialias(true); paint.setstrokewidth(5f); paint.setcolor(color.black); paint.setstyle(paint.style.stroke); paint.setstrokejoin(paint.join.round); }
you can have empty constructor like
public drawingview() { }
Comments
Post a Comment