ViewStub vs View.GONE vs Inflate vs ViewSwitcher

In 2017, Android team published AsyncLayoutInflater on support library v24. In 2020, it's part of Jetpack library.

AsyncLayoutInflater is another way to inflate layout lazily. As the API documentation says

Helper class for inflating layouts asynchronously. To use, construct an instance of AsyncLayoutInflater on the UI thread and call inflate(int, ViewGroup, OnInflateFinishedListener). The AsyncLayoutInflater.OnInflateFinishedListener will be invoked on the UI thread when the inflate request has completed.

This is intended for parts of the UI that are created lazily or in response to user interactions. This allows the UI thread to continue to be responsive & animate while the relatively heavy inflate is being performed.

This is the code snippet to use AsyncLayoutInflater:

button.setOnClickListener { view ->
    val container = findViewById(R.id.container)
    val asyncLayoutInflater = AsyncLayoutInflater(this@MainActivity)
    asyncLayoutInflater.inflate(
        R.layout.view_sample,
        container,
        object : OnInflateFinishedListener() {
            fun onInflateFinished(view: View, resId: Int, parent: ViewGroup) {
                parent.addView(view)
            }
        }
    )
}

It's depending on the view you want to inflate itself. Every method you mentioned has it's own overhead and you need to decide where to compromise.

  1. If your view is quite simple and doesn't need to initialize much, just set it so View.GONE. If it's quite complex or a layout better don't do so.
  2. The ViewFlipper and ViewSwitcher are intended to animate between different views. Its purpose isn't to show and hide a single view. Use it if you have different views to display in the same place at different times.
  3. ViewStub is just a placeholder which replaces itself with a more complex layout.
  4. Doing everything manually is like using ViewStub just without having the layout information. If you have the need to create or setup the view programmatically, this might be a good choice though.