eralp
eralp

Reputation: 113

Removing or Adding views vs ViewStub

What is the difference between .remove() .addView() and using ViewStub? How ViewStub increasing layout render efficiency?

Upvotes: 1

Views: 1593

Answers (2)

hotpro
hotpro

Reputation: 336

ViewStub is the same as adding View in term of performance. Take a look at the ViewStub.inflate(). What it does is the adding view dynamically.

public View inflate() {
    ...
    final View view = factory.inflate(mLayoutResource, parent,
            false);
    ... 
    parent.addView(view, index, layoutParams);
    } else {
        parent.addView(view, index);
    }
    ...
    return view;
}

https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/view/ViewStub.java

Upvotes: 2

Leonardo
Leonardo

Reputation: 3191

As you can see in this article, when you use ViewStub, the layout that you <include /> inside the stub won't be inflated unless required (setting the visibility of the stub to VISIBLE or calling show()). The advantage is, none of the included view will be part of the view hierarchy, so your view is lighter.

See this example: ViewStub not inflated: enter image description here

After inflating: enter image description here

Of course you have a tradeoff here, when you set VISIBLE (or show()) a reinflate (only on the ViewStub layout) happens.

Upvotes: 2

Related Questions