Inflating a view outside of onCreateView in Fragment

106 Views Asked by At

Android docs teach us to inflate our xml layouts in onCreateView and than to return inflated view. But what about inflating in other places?

I want to inflate my view in constructor, store in a filed, and later just return it in onCreateView, already inflated. I can't do it in usual way. For this I must create an Inflater, and it seems to work:

class MyFragment : Fragment() 
{
    private var _view: View? = null

    constructor() {
        inflateView()
    }

    private fun inflateView() {
        _view = LayoutInflater.from(requireContext()).inflate(R.layout.my_layout, null, false)
    }

    ...

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return _view
    }
}

But docs say that I must inflate directly in onCreateView(). Why? Are there any drawbacks in this approach? What is the proper way to do this with my requirements?

2

There are 2 best solutions below

0
Michael Krause On

You might have a look at AsyncLayoutInflater.

This will allow for the actual view inflation to happen on a background thread and provides an OnInflateFinishedListener callback when inflation is finished.

There are a few restrictions on what can be inflated, so be sure to read the documentation carefully.

0
Pawel On

Returning null from onCreateView means you're creating a "headless fragments" (with no UI whatsoever).

This affects its behavior and lifecycle (no onViewCreated and onDestroyView is called, viewLifecycleOwner remains null).

If you intend to create view hierarchy lazily you have to at least return a barebone FrameLayout that you will populate later (or just create a "loading" layout and replace it).