设为首页 加入收藏

TOP

Android中LayoutInflater的使用
2014-11-24 07:17:38 来源: 作者: 【 】 浏览:0
Tags:Android LayoutInflater 使用

首先对LayoutInflater下一个定义吧,Layoutinflater的作用就是将一个xml布局文件实例化为View对象。


获取Layoutinflater对象的方法有三种,招不在多,管用就行,跟踪源码后发现三种方法的本质都是调用了context.getSystemService(),所以建议以后写的时候就用context.getSystemService()。具体写法如下:


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


接下来重点介绍inflate()方法的使用:


1、返回值:


View对象,有了View对象我们就能做诸如setContentView()或者在自定义Adapter里面的getView()方法中获取item的布局。


2、参数:


public View inflate (int resource, ViewGroup root)


第一个参数是一个xml文件的R索引,比如R.layout.activity_main。第二个参数如果不为null就是将得到的View对象再放入一个Viewgroup容器中,我这么说可能有的读者还不是很清楚,文章的最后会有一个例子来说明问题。


public View inflate (int resource, ViewGroup root, boolean attachToRoot)


这里的第三个参数的意思是如果第二个参数不为null,那么为true则放入第二个参数引用的Viewgroup中,为false则不放入第二个参数的Viewgroup中。


下面用一个实例来说明问题。

布局文件有两个:

activity_main.xml


android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />


android:id="@+id/viewgroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >



inflatertest.xml


< xml version="1.0" encoding="utf-8" >
http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >


android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="inflatedemo" />



当Activity中如是写:


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewGroup = (RelativeLayout) findViewById(R.id.viewgroup);
mInflater = (LayoutInflater) getApplicationContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
mInflater.inflate(R.layout.inflatertest, mViewGroup);
}


或者


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewGroup = (RelativeLayout) findViewById(R.id.viewgroup);
mInflater = (LayoutInflater) getApplicationContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
mInflater.inflate(R.layout.inflatertest, mViewGroup, true);
}


结果是这样子的:


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Android 程序导航页面appguide的.. 下一篇Android 网络操作常用的两个类

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·MySQL 安装及连接-腾 (2025-12-25 06:20:28)
·MySQL的下载、安装、 (2025-12-25 06:20:26)
·MySQL 中文网:探索 (2025-12-25 06:20:23)
·Shell脚本:Linux Sh (2025-12-25 05:50:11)
·VMware虚拟机安装Lin (2025-12-25 05:50:08)