BasePresenter
//定义一个泛型,起到占位的作用
public class BasePresenter<V> {
private WeakReference<V> iView;
//定义一个变量,在P层中调用
protected V myView;
//定义一个方法用来获得View
protected void AttchView(V view){
//将传入的View放入若引用中,可以优化内存,及时回收
iView = new WeakReference<>(view);
//给这个变量赋值,值就是传进来的View
myView = iView.get();
}
//定义一个方法用来回收变量,在页面销毁的时候调用此方法
protected void onDestroy(V view){
if(view != null){
iView.clear();
myView = null;
iView = null;
}
}
}
BaseActivity
public abstract class BaseActivity<V extends BaseView,P extends BasePresenter<V>> extends Activity {
//定义一个presenter是为了在子类中直接调用,下面会给他赋值并实例化
@Inject
protected P presenter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
//这个方法是为了注册dagger2,就是将上面的presenter指向一个类
inject();
super.onCreate(savedInstanceState);
setContentView(getContentView());
//给presenter赋值
presenter.AttchView((V) this);
initView();
initData();
}
protected abstract void inject();
//获得布局文件
protected abstract int getContentView();
protected abstract void initView();
protected abstract void initData();
//这个方法是为了实例化dagger2
protected MyComponent getMyComponent(){
return DaggerMyComponent.builder().build();
}
//重写销毁的方法,将变量进行回收,避免内存泄露
@Override
protected void onDestroy() {
super.onDestroy();
//调用BasePresenter里面的销毁方法,回收对象
presenter.onDestroy((V) this);
}
}