Android如何从另一个类别调用方法

问题描述:

现在我正在研究将在onClick上画线的应用程序。我正在LineView.java班上画线,并在MainActivity.java上表演onClick方法。为了解决这个问题,我检查了类似的问题。 第一个解决方案:Android如何从另一个类别调用方法

LineView.onDraw(); 

它给我这个错误:

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" 

我也试过在MainActivity写:

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

但它也提供了一个错误:

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" 

她E公司我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; 
} 

} 

MainActivity.javaonClick

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

提前感谢!

+0

你有没有将LineView添加到任何布局或动态初始化LineView? –

+0

是的。我在我的layout_main中有LineView –

你不应该直接在任何View上调用onDraw()。 视图绘制自己,如果它们是可见的,并在视图层次结构。 如果您需要的视图中绘制本身,因为事情已经改变(如您的A和B变量),那么你应该做这样的事情:

LineView.invalidate(); 

无效()告诉该观点已经改变了UI系统和应该在不久的将来调用onDraw()(可能是UI线程的下一次迭代)。

我认为你的'绘制'变量可能是不必要的。如果您想要隐藏视图,请使用setVisibility()。

+0

这不起作用。它说它不能从View类型中对非静态方法invalidate()进行静态引用。我不能以某种方式在MainActivity中使用onDraw()吗? –

+0

您需要对LineView类的实例调用invalidate,而不是类本身。如果你没有对你的LineView对象的引用,那么你可以通过这种方式从你的布局中获得它''(LineView)mainView.findViewById(R.id.id_of_LineView);' –

+0

另请参阅这里:[链接](http: //stackoverflow.com/questions/3903537/i-want-to-know-the-difference-between-static-method-and-non-static-method) –