从调用者类中的视图实现方法

时间:2015-07-16 11:46:02

标签: android inheritance android-view

我有以下类扩展View:

public class MyCustomView extends View {
...
public void methodImplementedHere () { int a=1; }
@Override
public boolean onTouchEvent(MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
        case MotionEvent.ACTION_MOVE:
            methodImplementedHere ();
            methodImplementedInActivity();
            return true;
    }
    return false;
}
}

和活动:

public class MainActivity extends Activity {
private MyCustomView customView;
....
methodImplementedInActivity () {int b=4}
}

我可以在活动中实现该方法,但是在视图类中调用它吗?

1 个答案:

答案 0 :(得分:0)

您必须创建MyCustomView的实例,然后调用方法。

MyCustomView mcv = new MyCustomView();

mcv.methodImplementedHere();

或者您可以创建新的类,它将扩展MyCustomView并覆盖方法。

public class SecondCustomView extends MyCustomView {
    public SecondCustomView(param...) {
    super(param...)
  }
  @Override
  public void methodImplementedHere() { int a = 4 }
}

并在活动中调用

SecondCustomView scv = new SecondCustomView(param...) 
scv.methodImplementedHere(); // int a = 4;