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?
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.