1. LayoutInflater基本用法

LayoutInflater的基本用法,首先需要获取到LayoutInflater的实例,有两种方法可以获取到

第一种写法如下:

LayoutInflater layoutInflater = LayoutInflater.from(context);

第二种写法,也可以完成同样的效果:

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

其实第一种就是第二种的简单写法,只是Android给我们做了一下封装而已。

2. 调用inflate()方法加载布局

得到了LayoutInflater的实例之后就可以调用它的inflate()方法来加载布局了,如下所示:

layoutInflater.inflate(resourceId, root);
  • 第一个参数就是要加载的布局id,
  • 第二个参数是指给该布局的外部再嵌套一层父布局,如果不需要就直接传null。

这样就成功成功创建了一个布局的实例,之后再将它添加到指定的位置就可以显示出来了。


举例1:layoutInflater.inflate(resourceId,root);

下面通过一个非常简单的小例子,来更加直观地看一下LayoutInflater的用法;

MainActivity对应的布局文件叫做activity_main.xml,代码如下所示:

 

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

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

这个布局文件只有一个Button按钮。

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

public class MainActivity extends Activity { private LinearLayout mainLayout; @Overrideprotected 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的身影。


举例2:inflate(int resource,ViewGroup root,boolean attachToRoot);

inflate()方法还有个接收三个参数的方法重载,结构如下:

inflate(int resource, ViewGroup root, boolean attachToRoot)
  • 如果root为null,attachToRoot将失去作用,设置任何值都没有意义。
  • 如果root不为null,attachToRoot设为true,则会给加载的布局文件的指定一个父布局,即root。
  • 如果root不为null,attachToRoot设为false,则会将布局文件最外层的所有layout属性进行设置,当该view被添加到父view当中时,这些layout属性会自动生效。
  • 在不设置attachToRoot参数的情况下,如果root不为null,attachToRoot参数默认为true。

所以根据以上结论来看,如果我们item的布局是酱紫的:

<?xml version="1.0" encoding="utf-8"?>

如果你想让 android:layout_width 这些布局属性起作用的话,你应该这样写代码:

LayoutInflater.from(parent.getContext()).inflate(R.layout.item_tag, parent, false);

 

更多相关文章

  1. RK3288[android 7.1]调试笔记 去掉桌面上的谷歌搜索框
  2. android动态界面布局
  3. adb下的tcpdump抓包方法
  4. qt for android 实现开机自启
  5. Android培训班(40)
  6. Android百度地图之显示地图
  7. Android系列之Android(安卓)命令行手动编译打包详解
  8. android 相对布局,代码创建imageview,布局居中问题
  9. android使用字体

随机推荐

  1. 基于xml类型的压缩数据流的android获取天
  2. Android使用Http连接服务器,解析JSON, XML
  3. Android消息处理机制:Handler|Message
  4. Android分辨率
  5. Android(安卓)主题切换功能
  6. android中使用selector动态改变imageView
  7. Android 浏览器打开本地APK
  8. Android 自定义下拉列表
  9. Android记住用户
  10. Ice Cream Sandwich 为 Android 相机和相