Inflate and Fragment - Why should we use them?


#1

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?

Thanks,
doomoo


#2

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.”


#3

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?


#4

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:
http://stackoverflow.com/questions/17808177/difference-between-setcontentview-and-inflater