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)显示出来

     程序猿必读

  • 相关阅读:
    maven 依赖排除
    SpringMvc自动装配@Controller无效
    SpringMvc笔记-对RESTFUL风格的配置
    Shiro报错-[org.apache.shiro.mgt.AbstractRememberMeManager]
    According to TLD or attribute directive in tag file, attribute value does not accept any expressions报错解决办法
    shiro笔记-AuthenticatingRealm和AuthorizingRealm关系
    Shiro笔记--shiroFilter权限过滤
    maven使用jstl表达式和The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application解决
    mysql window版本下载
    linux中/bin和/sbin和/usr/bin和/usr/sbin
  • 原文地址:https://www.cnblogs.com/longzhongren/p/6073129.html
Copyright © 2011-2022 走看看