码迷,mamicode.com
首页 > 其他好文 > 详细

BaseFragment 基类代码

时间:2019-08-04 20:02:58      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:clear   UNC   nta   find   swa   private   www   detach   getview   


public abstract class BaseFragment extends Fragment implements IBaseView {

private List<BasePresenter> mInjectPresenters;

private View mLayoutView;

protected abstract @LayoutRes int setLayout();

protected abstract void initViews(@Nullable Bundle savedInstanceState);

protected abstract void initData();

@SuppressWarnings("ConstantConditions")
protected <T extends View> T $(@IdRes int viewId) {
return this.getView().findViewById(viewId);
}

@SuppressWarnings({"unchecked", "TryWithIdenticalCatches"})
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(setLayout(), container, false);

mInjectPresenters = new ArrayList<>();

//获得已经申明的变量,包括私有的
Field[] fields = this.getClass().getDeclaredFields();
for (Field field : fields) {
//获取变量上面的注解类型
InjectPresenter injectPresenter = field.getAnnotation(InjectPresenter.class);
if (injectPresenter != null) {
try {
Class<? extends BasePresenter> type = (Class<? extends BasePresenter>) field.getType();
BasePresenter mInjectPresenter = type.newInstance();
//绑定
mInjectPresenter.attach(this);
field.setAccessible(true);
field.set(this, mInjectPresenter);
mInjectPresenters.add(mInjectPresenter);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (java.lang.InstantiationException e) {
e.printStackTrace();
} catch (ClassCastException e) {
e.printStackTrace();
throw new RuntimeException("SubClass must extends Class:BasePresenter");
}
}
}
return view;
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);

initViews(savedInstanceState);
initData();
}

@Override
public void onDestroy(http://www.my516.com) {
super.onDestroy();
for (BasePresenter presenter : mInjectPresenters) {
presenter.detach();
}
mInjectPresenters.clear();
mInjectPresenters = null;
}
}
--------------------- 

BaseFragment 基类代码

标签:clear   UNC   nta   find   swa   private   www   detach   getview   

原文地址:https://www.cnblogs.com/ly570/p/11299107.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!