Android How to call a method from another class

I am currently working on an application that will draw a line on onClick

. I am drawing a line in a class LineView.java

and executing the method onClick

in MainActivity.java

. To solve this problem, I checked similar questions. First solution:

LineView.onDraw();

      

It gives me this error:

Multiple markers at this line
    - The method onDraw(Canvas) in the type LineView is not applicable for the 
     arguments ()
    - Suspicious method call; should probably call "draw" rather than "onDraw"

      

Also I tried to write in MainActivity:

LineView lineView = new LineView(null);
lineView.onDraw();

      

But this also gives an error:

Multiple markers at this line
    - The method onDraw(Canvas) in the type LineView is not applicable for the 
     arguments ()
    - Suspicious method call; should probably call "draw" rather than "onDraw"

      

Here's my LineView.java:

public class LineView extends View {
Paint paint = new Paint();
Point A;
Point B;
boolean draw = false;

public void onCreate(Bundle savedInstanceState) {

}

public LineView(Context context, AttributeSet attrs) {
  super(context, attrs);
  }

public LineView(Context context, AttributeSet attrs, int defstyle) {
super(context, attrs, defstyle );
  }


public LineView(Context context) {
super(context);
paint.setColor(Color.BLACK);
}

@Override
public void onDraw(Canvas canvas) {
    draw = MainActivity.draw;
    if(draw){
    //A = (getIntent().getParcelableExtra("PointA"));
    A = MainActivity.A;
    B = MainActivity.B;

    canvas.drawLine(A.x, A.y, B.x, B.y, paint);
    }
}

private Intent getIntent() {
    // TODO Auto-generated method stub
    return null;
}

}

      

My MainActivity.java

onClick

:

 @Override
       public void onClick(View v) {
           draw = true;
                       LineView.onDraw();
                     }
   });

      

Thanks in advance!

+3


source to share


1 answer


You shouldn't call onDraw () on any view directly. Views are drawn by themselves if they are visible and in the view hierarchy. If you need the view to draw because something has changed (for example, your variables A and B), you should do something like this:

LineView.invalidate();

      



invalidate () tells the UI system that the view has changed and onDraw () should be called at some point in the near future (possibly the next iteration of the UI thread).

I think your "draw" variable is probably unnecessary. If you want to hide the view sometimes, use the setVisibility () function instead.

0


source







All Articles