【Android】加载布局的三种方式

第一种加载View的方法

View view = LayoutInflater.from(context).inflate(R.layout.activity_main, null);

第二种加载View的方法

View view = View.inflate(context, R.layout.activity_main, null);

第三种加载View的方法

LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.activity_main, null);


这里赋值的null是容器 (ViewGroup container),如果指定容器,则会把加载的View add 到容器当中

View.inflate(); 此静态方法是用的是LayoutInflater类的inflate方法

直接穿null参数可能会包黄:

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);
发布了27 篇原创文章 · 获赞 33 · 访问量 9504

猜你喜欢

转载自blog.csdn.net/qq_42470947/article/details/104266923