I read the answer on Why does LayoutInflater ignore the layout_width and layout_height layout parameters I've specified? and wanted to make sure i understood what attach to root does.
Basically if you do
inflater.inflate(int idOfLayoutFile, ViewGroup parent, boolean AttachToRoot)
and lets say parent is not null
From what I got out of that answer was that attach to root just affects what the return type is of the inflate method. That is if attachToRoot
is true
, method will return parent, and if it is false
, the method will return the root view of the XML file as specified by the resource id. Do I have the right idea here or am I missing something?
No, something is missed!
When you pass true
as 'attach to root', inflater will inflate specified layout (represented by its ID) and then attach it to root of parent and finally return the parent
But when you left 'attach to root' to false
. the parent hierarchy won't changed and only inflated layout will be returned.
Yes you are correct :: In short terms
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = LayoutInflater.from(getActivity()).inflate(
R.layout.your_layout, null);
return view;
}
- Now as per above code
view
reference will hold the root element for
the layout your_layout
- You can use this
view
reference to find all the child views of this
parent layout
- You can refer the child
views
here even though the activity
is not
created yet
If you read this you'll find that you should NOT pass null
as value of root ViewGroup
if you do not want to attach it but rather should use the 3-parameter version of inflater.inflate
with 3rd parameter (attach to root) set to false
. I.e., do this:
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState)
{
View view = LayoutInflater.from(getActivity()).inflate
(
R.layout.your_layout,
container,
false
);
return view;
}
And from the docs:
root
Optional view to be the parent of the generated hierarchy (if attachToRoot is true), or else simply an object that provides a set of LayoutParams
values for root of the returned hierarchy (if attachToRoot is false.)
And this is really good.