Android:LayoutInflater的作用及使用

来源:互联网 发布:淘宝超人软件 编辑:程序博客网 时间:2024/06/01 08:10

(1)释义

    inflate,原意:充气、膨胀、扩大。
    LayoutInflater可以理解为layout的扩展器。

(2)简介/对比

    LayoutInflater的作用类似于findViewById(),不同点是LayoutInflater是用来找layout文件夹下的xml布局文件,并且实例化;而findViewById()是找具体某一个xml下的具体widget控件(如:Button,TextView等)。

(3)详细/区分:
    1、对于一个没有被载入或者想要动态载入的界面,都需要使用inflate来载入。(如BaseAdapter的getView中,自定义Dialog中取得view中的组件widget等等)

    2、对于一个已经载入的Activity,就可以使用实现了这个Activiyt的的findViewById方法来获得其中的界面元素。

(4)方法:
    Android里面想要创建一个画面的时候,初学一般都是新建一个类,继承Activity基类,然后在onCreate里面使用setContentView方法来载入一个在xml里定义好的界面。
    其实在Activity里面就使用了LayoutInflater来载入界面,通过getSystemService(Context.LAYOUT_INFLATER_SERVICE)方法可以获得一个 LayoutInflater,也可以通过LayoutInflater inflater = getLayoutInflater()来获得.然后使用inflate方法来载入layout的xml。

(5)代码示例

    第一种方法:

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

    第二种方法:

LayoutInflater inflater = getLayoutInflater();View layout = inflater.inflate(R.layout.main, null);

    第三种方法:

LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);View layout = inflater.inflate(R.layout.main, null);