0

I've read this answer : https://stackoverflow.com/a/5027921/1364174

And wonder why depending on the root parameter inflate method changes its behavior such drastically creating confusion.

According to that answer this code:

view = LayoutInflater.from(getBaseContext()).inflate(R.layout.smallred, null);
parent.addView(view);

Will create will create view specified in smallred.xml completely ignoring the properties of tags replacing them with some mysterious defaults values.

But this code will respect the properties from smallred.xml

view = LayoutInflater.from(getBaseContext()).inflate(R.layout.smallred, parent, false);
parent.addView(view);

Why is that ? Why we need to specify root/parent to which we later insert our view to, nflate" method? Why is that necessary ? Why if we wouldn't we won't get the properties from .xml file ?

Community
  • 1
  • 1
Paweł Brewczynski
  • 2,665
  • 3
  • 30
  • 43
  • Do you want to know why the designers created the API this way? Do you want to know what uses both variants of inflate have? Do you want to know the underlying code to see why the API behaves how it does? ... Otherwise, why ask why? It is that way, always has been, and you get used to it. (For design, I'd guess performance reasons, but it would only be a guess...) – lilbyrdie Sep 15 '13 at 19:14
  • 1
    @lilbyrdie To be honest... Yes I would like to know the answer on each of those questions. But I'm afraid I won't get them. – Paweł Brewczynski Sep 15 '13 at 19:41

1 Answers1

0

Probably because attributes are read only when you are actually inflating the view, so once you inflate it without providing the parent you will be missing information inside the inflated view. Then it doesn't matter if you add it to a parent, the data isn't there so the layout won't be as you expected it to be.

The layoutinflater doesn't know about your parent when he's inflating your view. So it doesn't even know its class. If you notice, every layout has its own LayoutParams class inside it, and you have to tell the layoutinflater which one it has to use or they will be simply discarded.

LuigiPower
  • 1,113
  • 10
  • 20
  • It doesn't respect view's properties NOT parent's. – Paweł Brewczynski Sep 15 '13 at 20:00
  • But the view's properties depend on the type of parent it is put into. A view inside a RelativeLayout is different than one in a TableLayout no? – LuigiPower Sep 15 '13 at 20:59
  • 1
    The _layout properties_ are different. The _view properties_ are not. The layout properties, however, aren't part of the view object. Layout properties generally are applied when a view is added to a holder view of some kind. The fact that they're part of the view properties in XML doesn't mean they're part of the view object itself. – lilbyrdie Sep 16 '13 at 20:28