How to pass fragment layout inside BaseFragment()

Viewed 533

I have a BaseFragment that extends from Fragment

Currently my BaseFragment is this

open class BaseFragment : Fragment() {

    private lateinit var onInteractionListener: OnFragmentInteractionListener

    val toolbar : Toolbar?
        get() {
            return if(activity is BaseActivity)
                (activity as BaseActivity).toolbar
            else
                null
        }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        setOnInteractionListener(context)
    }
...

The thing is that when I extend this fragment I need to use onCreateView as always, but what I want to accomplish is to use the fragment layout inside the BaseFragment(LayoutResource) as optional when extending just like the Fragment overload method

/**
     * Alternate constructor that can be used to provide a default layout
     * that will be inflated by {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}.
     *
     * @see #Fragment()
     * @see #onCreateView(LayoutInflater, ViewGroup, Bundle)
     */
    @ContentView
    public Fragment(@LayoutRes int contentLayoutId) {
        this();
        mContentLayoutId = contentLayoutId;
    }

How can I implement this functionality inside my BaseFragment ? so when I extend it I can do

class A: BaseFragment(R.layout.myFragment)

or

class A: BaseFragment()

onCreateView(...) { ... }

Thanks !

1 Answers

Just have your primary constructor pass down an argument to super constructor. Provide default value of zero and you can use it as no-arg constructor as well:

open class BaseFragment(@LayoutRes contentLayoutId : Int = 0) : Fragment(contentLayoutId) {

    /// your class body

}
Related