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:
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!
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.
View.GONE
. If it's quite complex or a layout better don't do so.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.ViewStub
is just a placeholder which replaces itself with a more complex layout.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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With