关于LayoutInflater

来源:互联网 发布:js 导航栏点击后变色 编辑:程序博客网 时间:2024/05/29 02:35

原地址:http://blog.csdn.net/u012575819/article/details/51235051


LayoutInflater用于Layout XML文件解析,得到相应的View。

有三种得到LayoutInflater的方法:

LayoutInflater inflater = Activity.getLayoutInflater();LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);LayoutInflater inflater = LayoutInflater.from(context);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

三种方法在本质上都是一样的。 
上次在做自定义Toast时,需要将自定义的Toast Layout拿到,并用

Toast.setView(view);
  • 1
  • 1

方法设置到Toast中。

当时我是这样设置的:

LayoutInflater inflater = LayoutInflater.from(context);View layout = inflater.inflate(R.layout.toast. null);toast.setView(view);
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

这里想到得到Layout文件所对应的View对象,需要使用

LayoutInflater.inflate();
  • 1
  • 1

方法。 
问题在于这个方法有多个重载方法。 
1.LayoutInflater.inflate(int ResId, ViewGroup root);

第一个参数是Layout文件的资源ID。 
第二个参数是ViewGroup类型,如果不为null,则将inflate得到的View作为子View添加到root中;如果第二个参数为null,则直接返回我们创建的视图。

2.LayoutInflater.inflate(int ResId, ViewGroup root, boolean attchToRoot);

和上个方法类似,只是多了一个boolean类型的attchToRoot。这个参数表示什么呢? 
分情况讨论: 
第一种情况:如果root为null,则attchToRoot没有意义,和第一个方法等价。

第二种情况,root不为null,且attchToRoot为true,表示将inflate得到的View对象作为子View添加到root中。

第三种情况:root不为null,而attchToRoot为false,则表示将root的LayoutParams设置到我们inflate得到的View中,但是并不会将root作为View的父视图。 
大概就是这样。

还有一个问题需要写出来。 
在做自定义Toast时,原本希望Layout文件中设置的Layout_height和Layout_width可以在Toast中体现出来,但是并没有。 
无论我如何设置Layout_height和Layout_width,toast中展现出来都是一样的效果。 
这我就很郁闷了。明明写了啊,为什么不起作用? 
后来才知道: 
layout_width和layout_height是对于布局来说的,事实上一个Layout文件最外层的layout_width和layout_height是不起作用的。这也是为什么名称前面要加一个”layout”的缘故。 
之所以我们平时写Layout文件最外层的layout_width和layout_height是起作用的,原因是Android自动在最外层添加了FrameLayout。有兴趣可以去验证一下。 
这样疑惑就解开了。我在Toast的layout最外层加了一个RelativeLayout,果然,原本的Layout_height和Layout_width都起作用了。 
这也给了我一个启发:以后再写类似这种Inflate Layout文件到View中,如果想让Layout文件最外层的Layout_width和Layout_height起作用,就在最外层再添加一个Layout。


0 0