【问题标题】:Android How to Call Method From Another ClassAndroid 如何从另一个类调用方法
【发布时间】:2015-06-20 17:53:22
【问题描述】:

现在我正在开发将在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.javaonClick

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

提前致谢!

【问题讨论】:

  • 您是否已将 LineView 添加到任何布局或动态初始化 LineView?
  • 是的。我的 layout_main 中有 LineView

标签: java android main-activity


【解决方案1】:

您不应该直接在任何视图上调用 onDraw()。 如果视图可见并且在视图层次结构中,则视图会自行绘制。 如果您需要视图自行绘制,因为某些内容发生了变化(例如您的 A 和 B 变量),那么您应该执行以下操作:

LineView.invalidate();

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

我认为您的“绘制”变量可能是不必要的。如果您有时想隐藏视图,请改用 setVisibility()。

【讨论】:

  • 这不起作用。它说它不能从 View 类型中对非静态方法 invalidate() 进行静态引用。我不能在 MainActivity 中以某种方式使用 onDraw() 吗?
  • 您需要对 LineView 类的实例调用 invalidate,而不是类本身。如果您没有对 LineView 对象的引用,那么您可以通过这种方式从布局中获取它(LineView)mainView.findViewById(R.id.id_of_LineView);
  • 参见这里:link
猜你喜欢
  • 2015-03-27
  • 2019-06-22
  • 1970-01-01
  • 2015-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-20
相关资源
最近更新 更多