(Base Series III) basefragment basemvpffragment package

I'm in a bad mood. It's been a long time. Let's look at the BaseFragment code

private boolean isViewCreated;
protected boolean isInitData;

private Unbinder mUnBinder;
protected Context mContext;
private CompositeDisposable mCompositeDisposable;
private List<Observer> observerList;
private View view;

Declare some parameters. Two boolean variables are used to control the lazy loading of fragment s. Contentx is actually a BaseActivity object. It is unnecessary to use the getActivity() method, which sometimes returns null,

public void onAttach(Context context) {
    this.mContext = context;

Assign mContext

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    if (null == view) {
        view = inflater.inflate(getLayout(), container, false);
        mUnBinder = ButterKnife.bind(this, view);
        isViewCreated = true;
    } else {
        ViewGroup parent = (ViewGroup) view.getParent();
        if (null != parent) {
    return view;

protected abstract int getLayout();// Abstract method, subclass returns layout id

onCreateView method, null judgment can avoid an exception exposed by adding view many times. The specific exception name is a bit forgotten Failed to assign isViewCreated = true at the same time

public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    if(getUserVisibleHint()) {

public void setUserVisibleHint(boolean isVisibleToUser) {
    if(isVisibleToUser && isViewCreated && !isInitData) {

protected void initData() {
    isInitData = true;

This is the core code of lazy loading and avoiding repeated loading caused by switching fragments. initData() initialization is carried out when fragments are hidden and activities are created. In fact, the coupling feeling of this part is quite serious. The initData() method must be rewritten, otherwise the isinitData cannot be assigned. What's the good idea? I hope you can give me some advice

public void showLoadingDialog(String msg, boolean cancelable) {
    ((BaseActivity) mContext).showLoadingDialog(msg, cancelable);

Let's take this as an example. As in BaseActivity, it's ok to switch to mContext by force. All methods are synchronized with BaseActivity. In the same way, addDisposable, addObserver and their destruction principle are the same as BaseActivity. We won't go into details. This is actually a complete BaseFragment. Basemvpffragment code is more simple

public abstract class BaseMVPFragment<P extends BasePresenter> extends BaseFragment implements BaseView{
    protected P mPresenter;

One line of code . I'm really in a bad mood recently. I can't write well. I'll have time to edit again later.

Tags: Fragment ButterKnife

Posted on Sun, 09 Feb 2020 10:46:48 -0500 by Pr0digy