MVP模式
Presender 作为 View 与逻辑逻辑的桥梁
Android 模式中 Activity 实际上就是这个角色
ViewDelegate :view的代理。调用实例的view :xml,Linearlayout,自定view
如何使Activity 和 Fragment 成为优秀的 Presender
我定义了一下基类
Presender 基类,fragment与activity使用方法。
e.g
public abstract class BaseViewDelegateFragment<T extends BaseViewDelegate> extends Fragment {
protected T mViewDelegate;
public T getmViewDelegate() {
return mViewDelegate;
}
@Override
public final void onCreate(Bundle savedInstanceState) {
//因为没有使用框架,在此处初始化View.使用泛型,调用View的方法,给view赋予生命周期
createViewDelegate();
//给view设置逻辑调用
mViewDelegate.setFragment(this);
super.onCreate(savedInstanceState);
}
/**
* 创建viewdelegate,并绑定到fragment
*/
protected abstract void createViewDelegate();
@Override
public View onCreateView(LayoutInflater inflater
, ViewGroup container, Bundle savedInstanceState) {
//创建view并,给view赋值
mViewDelegate.create(inflater, null, savedInstanceState);
return mViewDelegate.create(inflater, null, savedInstanceState);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(view, savedInstanceState);
mViewDelegate.initWidget();//初始化组件
mViewDelegate.initListener();//初始化组件监听
}
/*****************
*presender 给view赋值生命周期
*其实很少会用到。
*一般都是presender 生命周期调用 view的方法
**********************/
@Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
@Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
mViewDelegate.onPause();
}
public void popBack() {
mViewDelegate.hideSoftInputMethod();
FragmentUtil.popBackImmediate(getActivity());
}
}
通用的View基类,适用与用户交互时候用
public abstract class BaseViewDelegate <P extends BaseViewDelegateFragment> implements IViewDelegate {
/*************** INPUT METHOD **************************/
InputMethodManager imm;
/***************** 组件view ********************************************/
protected final SparseArray<View> mViews = new SparseArray<View>();//保存view的容器类
protected View rootView;//最外层的view
public abstract int getRootLayoutId();
/********** PRESENDER *************/
protected P mFragment;
public void setFragment(P mFragment) {
this.mFragment = mFragment;
}
@Override
public void create(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
int rootLayoutId = getRootLayoutId();
rootView = inflater.inflate(rootLayoutId, container, false);
}
@Override
public int getOptionsMenuId() {
return 0;
}
//一些presender生命周期,不建议使用,但是用暂停handler很有效,
//建议直接在presender生命周期,调用一些view的功能
public void onCreate() {
}
public void onResume() {
}
@Override
public View getRootView() {
return rootView;
}
public