【边做项目边学Android】知识点:动态设置布局LayoutInflater

一.作用:

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


二.获得 LayoutInflater 实例的三种方式

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

2.LayoutInflater inflater = LayoutInflater.from(this);

3.LayoutInflater inflater = (LayoutInflater)Context.getSystemService(LAYOUT_INFLATER_SERVICE);

其实,这三种方式本质是相同的,从源码中可以看出:

getLayoutInflater():

Activity 的 getLayoutInflater() 方法是调用 PhoneWindow 的getLayoutInflater()方法,看一下该源代码:

public PhoneWindow(Context context) {
        super(context);
        mLayoutInflater = LayoutInflater.from(context);
}  

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

LayoutInflater.from(context):

public static LayoutInflater from(Context context) {
    LayoutInflater LayoutInflater =
            (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (LayoutInflater == null) {
        throw new AssertionError("LayoutInflater not found.");
    }
    return LayoutInflater;
}

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

结论:所以这三种方式最终本质是都是调用的Context.getSystemService()。


三.实例化LayoutInflater之后,就要将layout的xml布局文件实例化为View类对象。

1.

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

2.

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

3.

LayoutInflater inflater = (LayoutInflater)Context.getSystemService(LAYOUT_INFLATER_SERVICE);
View view=inflater.inflate(R.layout.ID, null);

四.inflate 方法

通过 sdk 的 api 文档,可以知道该方法有以下几种过载形式,返回值均是 View 对象,如下:

  • public View inflate (int resource, ViewGroup root)  (常用)

    • inflate()方法一般接收两个参数,第一个参数就是要加载的布局id,第二个参数是指给该布局的外部再嵌套一层父布局,如果不需要就直接传null。这样就成功成功创建了一个布局的实例,之后再将它添加到指定的位置就可以显示出来了。
  • public View inflate (XmlPullParser parser, ViewGroup root)
  • public View inflate (XmlPullParser parser, ViewGroup root, boolean attachToRoot)
  • public View inflate (int resource, ViewGroup root, boolean attachToRoot)

示意代码:

<pre name="code" class="java">LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custom, (ViewGroup)findViewById(R.id.test));
//EditText editText = (EditText)findViewById(R.id.content);// error
EditText editText = (EditText)view.findViewById(R.id.content);

对于上面代码,指定了第二个参数 ViewGroup root,当然你也可以设置为 null 值。


实例:

下面我们就通过一个非常简单的小例子,来更加直观地看一下LayoutInflater的用法。比如说当前有一个项目,其中MainActivity对应的布局文件叫做activity_main.xml,代码如下所示:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

</LinearLayout>

这个布局文件的内容非常简单,只有一个空的LinearLayout,里面什么控件都没有,因此界面上应该不会显示任何东西。

那么接下来我们再定义一个布局文件,给它取名为button_layout.xml,代码如下所示:

<Button xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button" >

</Button>

这个布局文件也非常简单,只有一个Button按钮而已。

现在我们要想办法,如何通过LayoutInflater来将button_layout这个布局添加到主布局文件的LinearLayout中。根据刚刚介绍的用法,修改MainActivity中的代码,如下所示:

public class MainActivity extends Activity {

    private LinearLayout mainLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mainLayout = (LinearLayout) findViewById(R.id.main_layout);
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        View buttonLayout = layoutInflater.inflate(R.layout.button_layout, null);
        mainLayout.addView(buttonLayout);
    }

}

可以看到,这里先是获取到了LayoutInflater的实例,然后调用它的inflate()方法来加载button_layout这个布局,最后调用LinearLayout的addView()方法将它添加到LinearLayout中。

现在可以运行一下程序,结果如下图所示:

Button 在界面上显示出来了!说明我们确实是借助LayoutInflater成功将button_layout这个布局添加到LinearLayout中了。 LayoutInflater技术广泛应用于需要动态添加View的时候,比如在ScrollView和ListView中,经常都可以看到 LayoutInflater的身影。



参考:

http://www.cnblogs.com/merryjd/archive/2013/01/08/2851092.html

http://blog.csdn.net/guolin_blog/article/details/12921889

时间: 2024-08-25 05:31:35

【边做项目边学Android】知识点:动态设置布局LayoutInflater的相关文章

【边做项目边学Android】知识点:Intent

一. Intent的介绍 Android中提供了Intent机制来协助应用间的交互与通讯,或者采用更准确的说法是,Intent不仅可用于应用程序之间,也可用于应用程序内部的activity, service和broadcast receiver之间的交互. Intent是一种运行时绑定(runtime binding)机制,它能在程序运行的过程中连接两个不同的组件.通过Intent,你的程序可以向Android表达某种请求或者意愿,Android会根据意愿的内容选择适当的组件来响应. Inten

【边做项目边学Android】知识点:Adapter适配器

1.概念 Adapter是连接后端数据和前端显示的适配器接口,是数据和UI(View)之间一个重要的纽带.在常见的 View(ListView,GridView)等地方都需要用到Adapter.如下图直观的表达了Data.Adapter.View三者的关系: Android中所有的Adapter一览: 由图可以看到在Android中与Adapter有关的所有接口.类的完整层级图.在我们使用过程中可以根据自己的需求实现接口或者继承类进行一定的扩展.比较常用的有 BaseAdapter,Simple

【边做项目边学Android】知识点:SharedPreferences

Ⅰ. 简介 很多时候我们开发的软件需要向用户提供软件参数设置功能,例如我们常用的 QQ,用户可以设置是否允许陌生人添加自己为好友.对于软件配置参数的保存,如果是window软件通常我们会采用ini文件进行保存,如果是j2se应用,我们会采用properties属性文件或者xml进行保存.如果是Android应用,我们最适合采用什么方式保存软件配置参数呢?Android 平台给我们提供了一个SharedPreferences类,它是一个轻量级的存储类,特别适合用于保存软件配置参数.SharedPr

【边做项目边学Android】知识点:Android控件系列之ProgressDialog与ProgressBar

ProgressDialog ProgressDialog与ProgressBar在UI中动态显示一个加载图标显示程序运行状态. ProgressDialog是继承自Android.app.AlertDialog所设计的互动对话窗口,使用时,必须新建ProgressDialog对象,在运行时会弹出"对话框"作为提醒,此时应用程序后台失去焦点(即此时无法对UI组件进行操作),直到进程结束后,才会将控制权交给应用程序,如果在Activity当中不希望后台失焦,又希望提示User有某后台程序

【边做项目边学Android】手机安全卫士01:splash界面ui

手机安全卫士项目是跟着黑马的视频做的. splash是飞洒.飞溅的意思,主要是用于完成一个产品logo显示,期间可以: 后台完成数据库初始化的操作 联网访问服务器,获取服务器最新信息(升级提示) 不同的日期显示出来不同logo,判断当前系统时间,素材一般从服务器上下载下来. 判断时间,根据不同时间显示不同的加载页面 布局文件:splash.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayou

【边做项目边学Android】异常处理:android.os.NetworkOnMainThreadException--多线程问题

一切搞定.以为高枕无忧了,结果还是有问题! log開始报错了,获取更新信息异常..!debug一下.发现Exception:android.os.NetworkOnMainThreadException 这个异常大概意思是在主线程訪问网络时出的异常. Android在4.0之前的版本号 支持在主线程中訪问网络.可是在4.0以后对这部分程序进行了优化,也就是说訪问网络的代码不能写在主线程中了. 查看网上的解决方法.在Android中实现异步任务机制有两种方式,Handler和AsyncTask.

【边做项目边学Android】小白会遇到的问题--Appcompat_V7问题

问题描写叙述: 首先遇到的问题就是adt版本号的选择,sdk版本号的选择: adt按非小白朋友说的选了最新的ADT-22.3.0,同一时候我也把sdk更新到了最新的(嗯.这个要fanqiang,或者找离线包). 非常开心啊,认为能够開始啦.于是新建Android项目.next-->next...finish!项目生成! (当然中间要填写东西) 项目建成了,发现Eclipse自己主动生成了一个奇怪的项目Appcompat_V7项目,再创建一个Android项目时,又会再多出一个appcompat_

【边做项目边学Android】手机安全卫士03:获取更新的服务器配置,显示更新对话框

配置应用程序在手机桌面显示的名称和图标-AndroidManifest.xml: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.liuhao.mobilesafe" android:versionCode="

【边做项目边学Android】手机安全卫士04_01:界面(Activity)之间的切换,Activity和任务栈

上一回说到,用户选择是否升级,若用户选择不升级,那么就要进入程序的主界面.下面要做的是从splash界面跳转到main界面. MainActivity创建 1.首先新建MainActivity: package com.liuhao.mobilesafe.ui; import com.liuhao.mobilesafe.R; import android.app.Activity; import android.os.Bundle; public class MainActivity exten