zoukankan      html  css  js  c++  java
  • Android中LayoutInflater的使用

    在实际工作中,事先写好的布局文件往往不能满足我们的需求,有时会根据情况在代码中自定义控件,这就需要用到LayoutInflater。
    LayoutInflater在Android中是“扩展”的意思,作用类似于findViewById(),不同的是LayoutInflater是用来获得布局文件对象的,而

    findViewById()是用来获得具体控件的。LayoutInflater经常在BaseAdapter的getView方法中用到,用来获取整个View并返回。

    实现LayoutInflater的实例化共有3种方法,

    (1).通过SystemService获得

        LayoutInflaterinflater = (LayoutInflater)context.getSystemServices(Context.LAYOUT_INFLATER_SERVICES);

        Viewview = inflater.inflate(R.layout.main, null);

    (2).从给定的context中获得

        LayoutInflaterinflater = LayoutInflater.from(context);

        Viewview = inflater.inflate(R.layout.mian, null);

    (3).LayoutInflaterinflater =getLayoutInflater();(在Activity中可以使用,实际上是View子类下window的一个函数)

        Viewlayout = inflater.inflate(R.layout.main, null);

    从源码中可以看出,这三种方法本质是一样的。

    源代码:

        publicPhoneWindow(Contextcontext) {

            super(context);

            mLayoutInflater= LayoutInflater.from(context);

        }

    可以看出它其实是调用LayoutInflater.from(context)。

    LayoutInflater.from(context):

        public static LayoutInflaterfrom(Context context) {

            LayoutInflaterLayoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            if(LayoutInflater== null){

                thrownew AssertionError("LayoutInflaternot found.");

            }

            returnLayoutInflater;

        }

    可以看出它其实调用context.getSystemService()。

    public View inflate(int Resource,ViewGroup root)
    作用:从指定的XML资源文件中拓展一个新的视图层次结构
    Resource:要加载的XML资源文件的ID
    root: 生成的层次结构的根视图(可选)
    return 拓展的层次结构的根视图。如果提供了root,那么root就是根视图;否则根视图是拓展的XML文件的根视图。

    另外getSystemService()是Android很重要的一个API,它是Activity的一个方法,根据传入的NAME来取得对应的Object,然后转换成相应的服务对象。以下介绍系统相应的服务。

    传入的Name           返回的对象      说明

    WINDOW_SERVICE      WindowManager      管理打开的窗口程序
    LAYOUT_INFLATER_SERVICE      LayoutInflater      取得xml里定义的view
    ACTIVITY_SERVICE      ActivityManager      管理应用程序的系统状态
    POWER_SERVICE      PowerManger      电源的服务
    ALARM_SERVICE      AlarmManager      闹钟的服务

    NOTIFICATION_SERVICE      NotificationManager      状态栏的服务

    KEYGUARD_SERVICE      KeyguardManager      键盘锁的服务
    LOCATION_SERVICE      LocationManager      位置的服务,如GPS
    SEARCH_SERVICE      SearchManager      搜索的服务
    VEBRATOR_SERVICE      Vebrator      手机震动的服务
    CONNECTIVITY_SERVICE      Connectivity      网络连接的服务
    WIFI_SERVICE      WifiManager Wi-Fi     服务
    TELEPHONY_SERVICE      TeleponyManager      电话服务

  • 相关阅读:
    php无法连接mongodb 3.0问题解决
    mongodb安全配置
    RedHat6/Centos6.5安装mongodb php driver
    RedHat6/Centos6.5安装mongodb
    ASP.NET Identity 2集成到MVC5项目--笔记02
    ASP.NET Identity 2集成到MVC5项目--笔记01
    C#实体类序列化为XML
    MVC4学习笔记之--身份认证过滤器
    【WPF】学习笔记(三)——这个家伙跟电子签名板有个约定
    【WPF】学习笔记(二)——依旧是一个电子签名板
  • 原文地址:https://www.cnblogs.com/leihupqrst/p/3140432.html
Copyright © 2011-2022 走看看