第一种加载View的方法
View view = LayoutInflater.from(context).inflate(R.layout.activity_main, null);
第二种加载View的方法
View view = View.inflate(context, R.layout.activity_main, null);
View.inflate(); 此静态方法是用的是LayoutInflater类的inflate方法
第三种加载View的方法
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.activity_main, null);
传null作用
上面三种方式传递参数的null:是容器 (ViewGroup container),如果指定容器,则会把加载的View add 到容器当中。
直接穿null参数,IDE可能会报黄,解决办法:
Avoid passing null as the view root (needed to resolve layout parameters on the inflated layout's root element)
// 解决方法
ViewGroup container = null;
view = LayoutInflater.from(this).inflate(R.layout.activity_main, container);