Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewStub vs View.GONE vs Inflate vs ViewSwitcher

I've a question related to lazily loading a views / layout performance. Sometimes we want to dynamically show / hide multiple view. In this case, we have four options:

  1. Include all layout in .xml and use setVisibility method (like View.GONE and VIEW.VISIBLE)
  2. Using a ViewFlipper / ViewSwitcher
  3. Using a ViewStub
  4. Programmatically inflating new layouts.

Which one has the best performance? I've been Googling around and found that ViewStub is specifically designed for that, but I'm not sure about it. Maybe I was wrong or maybe there's even a fifth option that I didn't know. Do you have different opinion or experience related to this? Thanks!

like image 871
aldok Avatar asked Sep 08 '16 07:09

aldok


2 Answers

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)
            }
        }
    )
}
like image 63
aldok Avatar answered Nov 13 '22 01:11

aldok


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.
like image 31
tynn Avatar answered Nov 13 '22 01:11

tynn