标题栏完美复用,BaseTitleFragment(配合ViewSub,抽象方法)

一句话:有些人很疑惑怎么继承一个包含toolbar的Fragment让他直接成为你的标题栏?而不是把标题栏弄成自定义控件?

(这个是BaseTitleFragment的布局。)

接下来只需要获取继承BaseTitleFragment的碎片的layoutId,填充进这个ViewSub即可(ViewSub有助于优化性能)

@Override
protected void onBindViewBefore() {
    super.onBindViewBefore();
    // on before onBindViewBefore call
    ViewStub stub = (ViewStub) findViewById(R.id.view_stub);
    stub.setLayoutResource(getLayoutId());
    stub.inflate();
}

protected abstract int getLayoutId();
子类中

@Override
protected int getLayoutId() {
    return R.layout.fragment_course;
}



接下来的可以不看。save your time。

(全部代码)

BaseFragment

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    if (mRoot != null) {
        ViewGroup parent = (ViewGroup) mRoot.getParent();
        if (parent != null)
            parent.removeView(mRoot);
    } else {
        mRoot = inflater.inflate(getLayoutId(), container, false);
        mInflater = inflater;
        // Do something
        onBindViewBefore(mRoot);
        // Bind view
        ButterKnife.bind(this, mRoot);
        // Get savedInstanceState
        if (savedInstanceState != null)
            onRestartInstance(savedInstanceState);
        // Init
        initData();
        initWidget(mRoot);
    }
    return mRoot;
}
BaseTitleFragment

public abstract class BaseTitleFragment extends BaseFragment {

    @BindView(R.id.toolbar)
    protected Toolbar toolbar;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_base_title;
    }

    @Override
    protected void initWidget(View root) {
        super.initWidget(root);

        ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
    }

    @Override
    protected void onBindViewBefore(View root) {
        super.onBindViewBefore(root);
        // on before onBindViewBefore call
        ViewStub stub = (ViewStub) root.findViewById(R.id.view_stub);
        stub.setLayoutResource(getContentLayoutId());
        stub.inflate();
    }

    protected abstract int getContentLayoutId();
}
子类中

@Override
protected int getContentLayoutId() {
    return R.layout.fragment_course;
}