Inflate and Fragment - Why should we use them?


Sorry, this should be a basic question, but I’m really wondering on this.

Inflate: I read the book and roughly know how to use it but still don’t understand why we need it.
What I learnt is that Layout can use inflater to add views which is XML file.
But why can’t we just make Layout including all required views?

Fragment: I understand the situation if one screen needs to be divided such as tablet.
But why we should use this for a phone if it doesn’t need to separate the screen?

So, common question is, could you tell me an example which cannot be implemented if it doesn’t use inflater?
Also, one layout with one fragment?



The xml is just a blueprint. The layout doesn’t exist until you inflate it. Even if you forego xml and build a layout in code, it’s still just a plan until you inflate it.

As for your fragment question, the authors answered it directly on p. 147 in the section “The Reason All Our Activities Will Use Fragments.”


embeddedmatt, thank you for quick reply.

I know what you’re trying to say on inflater and I saw similar explanation at many places.

Then let me ask this:
What is the drawback if I call SetContentView() from Layout with XML which has all views I need comparing to inflating each view?


According to the book on p. 16, setContentView() inflates a layout. I looked in the Android documentation and it doesn’t use the word “inflate” in the description of setContentView() but it seems as though that method must cause the layout to be inflated. setContentView() is a method of Activity so it can’t be called on a Fragment. The method used to inflate a Fragment’s layout has a different name but it does the same job. And there is no need to inflate one View at a time. Inflate the parent View, layout, whatever… and all the children will be inflated too, right?

Similar discussion: