加载布局文件我们常用的方法是隐式方法setContentView()。今天总结了以下三个显式实例化的方法。
1) 通过getLayoutInflater()方法
View demo = getLayoutInflater().inflate(R.layout.activity_main, null);
2) 通过系统服务
LayoutInflater inflate = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View demo = inflate.inflate(R.layout.activity_main, null);
3) 通过已有LayoutInflater对象的副本
LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
View demo = inflater.inflate(R.layout.activity_main, null);
以上三种方法得到的View demo均可动态加载其他控件。第三种方法通过源代码可以看出还是使用了方法2,所以可以认为是一种方法,源码如下:
/**
* Obtains the LayoutInflater from the given context.
*/
public static LayoutInflater from(Context context) {
LayoutInflater LayoutInflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (LayoutInflater == null) {
throw new AssertionError("LayoutInflater not found.");
}
return LayoutInflater;
}