对于非空的 ViewGroup rooter,以下两句是等效的:
View view = inflater.inflate(R.layout.linearlayout, ll, false);
ll.addView(view);
与
View view = inflater.inflate(R.layout.linearlayout, ll, true);
他们的参数设置是有效果的,如图所示:
当第二个参数为null,第三个参数为false时(即使为true显示效果也是一样的,这里以false为例),由于在inflate方法中没有将linearlayout添加到某一个容器中,所以我需要手动添加,另外由于linearlayout并没有处于某一个容器中,所以它的根节点的宽高属性会失效,显示效果如下:
示例代码:
activity_main.xml:
linearlayout.xml:
MainActivity.java:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout ll = findViewById(R.id.ll);
LayoutInflater inflater = LayoutInflater.from(this);
//第三个参数为true写法:
View view = inflater.inflate(R.layout.linearlayout, null, true);
// 第三个参数为false写法:
// View view = inflater.inflate(R.layout.linearlayout, null, false);
// ll.addView(view);
}
}
inflate方法的参数关系
-
root != null, attachToRoot == true
传进来的布局会被加载成为一个View并作为子View添加到root中,最终返回root; 而且这个布局根节点的android:layout_xxx参数会被解析用来设置View的大小; -
root == null, attachToRoot无意义
当root为空时,attachToRoot无论是什么都没有意义。此时传进来的布局会被加载成为一个View并直接返回; 布局根View的android:layout_xxx
属性会被忽略,即android:layout_xx属性只有依附在某个ViewGroup中才能生效; -
root != null, attachToRoot == false
传进来的布局会被加载成为一个View并直接返回。 布局根View的android:layout_xxx
属性会被解析成LayoutParams并设置在View上,此时root只用于设置布局根View的大小和位置。
参考博客:
https://blog.csdn.net/u012702547/article/details/52628453