BaseFragment base class code


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) {
= Inflater.inflate View View (setLayout (), Container, to false);

mInjectPresenters new new = the ArrayList <> ();

// get variable has been declared, including proprietary
Field [] fields = this.getClass () getDeclaredFields (). ;
for (Field, Field,: Fields) {
// get the variables above annotation types
InjectPresenter injectPresenter = field.getAnnotation (InjectPresenter.class);
IF (injectPresenter = null!) {
the try {
Class of the type = (Class <<the extends BasePresenter?> ? the extends BasePresenter>) Field.getType ();
BasePresenter mInjectPresenter = type.newInstance ();
// bind
mInjectPresenter.attach (the this);
field.setAccessible (to true);
field.set (the 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;
}
}
--------------------- 

Guess you like

Origin www.cnblogs.com/ly570/p/11299107.html