安卓 LayoutInflater参数作用

  1. 方法重载1
    public View inflate (int resource, ViewGroup root, boolean attachToRoot)
  2. 方法重载2
    public View inflate (int resource, ViewGroup root)

直接结论

  1. 如果root为null,attachToRoot将失去作用,设置任何值都没有意义。

  2. 如果root不为null,attachToRoot设为true,则会在加载的布局文件的最外层再嵌套一层root布局。

  3. 如果root不为null,attachToRoot设为false,则root参数失去作用。

  4. 在不设置attachToRoot参数的情况下,如果root不null,attachToRoot参数默认为true.
  5. 在适配器adater中应使用inflate (R.layout.xxx, root,false);因为适配已经为我们填充出来的子view添加了一个父布局. 适配器使用的话会直接报错因为适配adapter会为我们填充的view帮我们添加到一个父布局,fragment同理

  • 如果采用重载2 的两种情况情况 (案例后面附上)

    1. 情况1
      child为布局填充出来的视图. root 为要添加的容器ViewGroup
      child= inflate (R.layout.xxx, null);
      root.addView(child)
      以上情况结果:

      • child中设置layout_width和layout_height将不起作用,大小改变为包裹内容
    2. 情况2
      child为布局填充出来的视图. root 为要添加的容器ViewGroup
      child= inflate (R.layout.xxx, root);
      root.addView(child)
      以上情况结果:

      • child中设置layout_width和layout_height不变
      • 本方法实际调用的是child= inflate (R.layout.xxx, root,true);
      • 适配器使用的话会直接报错因为适配adapter会为我们填充的view帮我们添加到一个父布局

案例详情点击此跳转

原文地址:https://www.cnblogs.com/muyuge/p/6152148.html