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

3

我现在正在开发一个应用程序,该应用程序将在 onClick 事件上绘制线条。我在 LineView.java 类中绘制线条,并在 MainActivity.java 中执行 onClick 方法。为了解决这个问题,我查看了类似的问题。

第一个解决方案:

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"

这是我的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.java中的onClick方法:

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

感谢您的提前帮助!

你是否将 LineView 添加到任何布局中或以动态方式初始化了 LineView? - Itzik Samara
是的,我在我的layout_main中有LineView。 - Oleksandr Firsov
1个回答

0

不应直接调用任何视图的onDraw()方法。 如果视图可见且在视图层次结构中,则会自行绘制。 如果您需要视图因某些更改(例如A和B变量)而自行绘制,则应执行以下操作:

LineView.invalidate();

invalidate()方法告诉UI系统视图已更改,onDraw()应在不久的将来(可能是下一个UI线程迭代)调用。

我认为你的“draw”变量可能是不必要的。如果您想有时隐藏视图,则应改用setVisibility()方法。


这个不起作用。它说无法从类型View中进行静态引用非静态方法invalidate()。我不能在MainActivity中以某种方式使用onDraw()吗? - Oleksandr Firsov
您需要在 LineView 类的实例上调用 invalidate,而不是类本身。如果您没有对 LineView 对象的引用,则可以通过以下方式从布局中获取它:(LineView)mainView.findViewById(R.id.id_of_LineView); - Joel Duggan
请参考这里:链接 - Joel Duggan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接