zoukankan      html  css  js  c++  java
  • 实例化Layout中的布局文件(xml)

    • 什么是LayoutInflater

      This class is used to instantiate layout XML file into its corresponding View objects.

    这个类作用是把把xml类型的布局转化成相应的View对象

    • 在实际开发中LayoutInflater这个类还是非常有用的,它的作用类似于findViewById()。

      不同点是LayoutInflater是用来找res/layout/下的xml布局文件,并且实例化;而findViewById()是找xml布局文件下的具体widget控件(如Button、TextView等)。

    具体作用: 1、对于一个没有被载入或者想要动态载入的界面,都需要使用LayoutInflater.inflate()来载入;

          2、对于一个已经载入的界面,就可以使用Activity.findViewById()方法来获得其中的界面元素。

    • LayoutInflater 实例化的三种方式
    1. LayoutInflater inflater = getLayoutInflater(); //调用Activity的getLayoutInflater()
    2. LayoutInflater localinflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); //context需定义
    3. LayoutInflater inflater = LayoutInflater.from(context); //context需定义

    通过源码分析,这三种方式最终的本质都是调用了Context.getSystemService()。

      实例化后通过inflate方法加载具体的布局资源。有以下几种方式:

    1. public View inflate (int resource, ViewGroup root) 
    2. public View inflate (XmlPullParser parser, ViewGroup root) 
    3. public View inflate (XmlPullParser parser, ViewGroup root, boolean attachToRoot) 
    4. public View inflate (int resource, ViewGroup root, boolean attachToRoot)

    解析:如果将root参数设置为null,则忽略xml布局文件中的layout_x参数,(一般情况下选择Null即可)

       如果root不为null,并且把attachToRoot=true,那么就会根据root生成一个布局文件View的LayoutParam对象,并且将这个View添加到root中去,并且返回这个root的View。

      具体例子:

    LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    View view = inflater.inflate(R.layout.custom, null); 
    EditText editText = (EditText)view.findViewById(R.id.content);
    • inflate方法与 findViewById 方法的区别
    1. inflater 是用来找 res/layout下的 xml 布局文件,并且实例化;
    2. findViewById() 是找具体 xml 布局文件中的具体 widget 控件(如:Button、TextView 等)。
    •  inflate方法与 SetContentView方法的区别
    1. SetContentView一旦调用, layout就会立刻显示UI
    2. inflate只会把Layout形成一个以view类实现成的对象。有需要时再用setContentView(view)显示出来

     程序猿必读

  • 相关阅读:
    使用bottle进行web开发(2):http request
    使用bottle进行web开发(1):hello world
    python modules
    python的class的__str__和__repr__(转)
    functools模块方法学习(1):partial
    bottle框架学习(2):变量定义等
    VisualSVN_Server安装_配置图文教程
    管理的艺术--达尔文进化论:适者生存 末位淘汰
    LINUX怎么修改IP地址
    Cent OS 命令行和窗口界面默认登录切换方法
  • 原文地址:https://www.cnblogs.com/longzhongren/p/6073129.html
Copyright © 2011-2022 走看看