首先得先在P层类名后加泛型
//在P层使用WeakReference管理外部类对象
public void attchView(T t){
//创建弱引用
tWeakReference = new WeakReference<>(t);
}
最后在P类最后加上解除关联的方法
//解除关联
public void deathView(){
if (tWeakReference.get()!=null){
tWeakReference.clear();
tWeakReference=null;
}
}
然后在主Activity里关联P层
// 关联 关联弱引用管理外部类对象
showPresenter.attchView(this);
最后在主Activity里重写 onDestroy方法
//解决mvp造成的内存泄漏
@Override
protected void onDestroy() {
super.onDestroy();
//activity销毁之前p必须先销毁
showPresenter.deathView();
Log.i(“zzz”,“销毁了”);
}