LayoutInflater及inflate方法

public void OnCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ...

这个是Activity创建时执行的方法,其中最后一句为加载布局的最简单的方法,但是如果,你需要动态加载布局,那就需要使用其他办法,如使用LayoutInfater的inflate方法。

获得 LayoutInflater 实例的三种方式

1).调用Activity的getLayoutInflater()
LayoutInflater inflater = getLayoutInflater(); 

2).LayoutInflater inflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

3).LayoutInflater inflater = LayoutInflater.from(context);

inflate()解析

public View inflate(int Resourece,ViewGroup root)
作用:填充一个新的视图层次结构从指定的XML资源文件中
reSource:View的layout的ID
root: 生成的层次结构的根视图

如果参数root提供了,那么root就是根视图;否则填充的XML文件的根就是根视图。其余几个重载的inflate函数类似。

下面的code和setContentView(R.layout.main)作用一样,但比较麻烦:

LayoutInflater inflate = LayoutInflater.from(this);
View view = inflate.inflate(R.layout.main,null);
setContentView(view);

猜你喜欢

转载自wander-bird.iteye.com/blog/2152967
今日推荐