您的位置:首页 > 移动开发 > Android开发

Android 加载布局文件的几种方式

2013-11-07 19:03 309 查看
加载布局文件我们常用的方法是隐式方法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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: