如何从一个Activity调用非静态方法到另一个Activity

时间:2016-09-14 11:38:16

标签: android android-activity

我有两项活动&我想从B中调出一个方法。 我试过这样,我得到空指针异常。

class A extends Activity {
    ...
    public void clear(){}

}

class B extends Activity{
    public void clearData() {
        A a=new A();
        a.clear();
    }        
}

1 个答案:

答案 0 :(得分:16)

class A extends Activity{
static A instance;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    instance = this;
}

public static A getInstance() {
    return instance;
}
....
public void clear(){}

}

和B组:

class B extends Activity {
  public void  clearData(){
      A a = A.getInstance();
      a.clear();
    }
}