Activity需要添加的方法
public class MainActivity extends AppCompatActivity implements ShowView {
private ShowPresenter presenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//关联 目的是为了使用弱引用管理外部类对象
presenter.attachView(this);
}
//解决mvp造成的内存泄漏
@Override
protected void onDestroy() {
super.onDestroy();
//activity销毁之前p得先销毁
presenter.detachView();
Log.i("xxx", "销毁了");
}
}
Presenter需要添加的方法
public class ShowPresenter<T> {
protected Reference<T> mViewRef;//View接口类型弱引用
//在p层使用WeakReference管理外部类对象
public void attachView(T t) {
//创建弱引用
mViewRef = new WeakReference<T>(t);
}
//解除关联
public void detachView() {
if (mViewRef.get() != null) {
mViewRef.clear();
mViewRef = null;
}
}
}