28

So I can inflate a ViewStub at runtime. Let's say I want to make it disappear and then maybe inflate again depending on some event occurring (for example, a toolbar that inflates and deflates according to what the user selects on screen).

I can use View.setVisibility(View.GONE).... is there any other way?

Or am I doing something wrong here?

Thanks! :)

Sid
  • 9,508
  • 5
  • 39
  • 60

2 Answers2

37

Inflating layouts can be expensive, especially on older devices. Think of ViewStub as more of a lazy-loading mechanism for view subtrees that may or may not ever get expanded rather than a way to swap out sections of a view hierarchy at runtime. Once inflated, there's nothing wrong with swapping between VISIBLE/GONE. GONE will make the framework skip that subtree during expensive traversals.

This is true as long as you don't need the memory used by the inflated view. Setting visibility to GONE doesn't release any memory whatsoever; it only marks the view as gone for layout and drawing purposes. To release the memory of the viewstub's inflated view, you would have actually to remove the inflated view and replace it again with a new viewstub for future use.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
adamp
  • 28,862
  • 9
  • 81
  • 69
  • hello @adamp I have one doubt. what if I create one simple linear layout and add one child view dynamically in it and when I don't need it I remove that child view from linear layout in this way it will remove child view completely. Is it good approach when you want memory optimization? because once view stub inflated we can't remove that view just by make it GONE. – KDeogharkar Aug 28 '14 at 05:23
0

Yes you can remove whenver you want .i have done it just now.

ViewStub stub = findById(...);
View v = stub.inflate();

and set view visibility on any event.

v.setVisibility(View.GONE);
Nachi
  • 4,218
  • 2
  • 37
  • 58
Tofeeq Ahmad
  • 11,935
  • 4
  • 61
  • 87