Clarification about layout inflater -attach to root?

坚强是说给别人听的谎言 提交于 2019-12-24 02:36:28

问题


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?


回答1:


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.




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/25225389/clarification-about-layout-inflater-attach-to-root

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!