转载请注明出处:http://blog.youkuaiyun.com/guolin_blog/article/details/12921889
有段时间没写博客了,感觉都有些生疏了呢。最近繁忙的工作终于告一段落,又有时间写文章了,接下来还会继续坚持每一周篇的节奏。
有不少朋友跟我反应,都希望我可以写一篇关于View的文章,讲一讲View的工作原理以及自定义View的方法。没错,承诺过的文章我是一定要兑现的,而且在View这个话题上我还准备多写几篇,尽量能将这个知识点讲得透彻一些。那么今天就从LayoutInflater开始讲起吧。
相信接触Android久一点的朋友对于LayoutInflater一定不会陌生,都会知道它主要是用于加载布局的。而刚接触Android的朋友可能对LayoutInflater不怎么熟悉,因为加载布局的任务通常都是在Activity中调用setContentView()方法来完成的。其实setContentView()方法的内部也是使用LayoutInflater来加载布局的,只不过这部分源码是internal的,不太容易查看到。那么今天我们就来把LayoutInflater的工作流程仔细地剖析一遍,也许还能解决掉某些困扰你心头多年的疑惑。
先来看一下LayoutInflater的基本用法吧,它的用法非常简单,首先需要获取到LayoutInflater的实例,有两种方法可以获取到,第一种写法如下:
- LayoutInflater layoutInflater = LayoutInflater.from(context);
- LayoutInflater layoutInflater = (LayoutInflater) context
- .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- layoutInflater.inflate(resourceId, root);
下面我们就通过一个非常简单的小例子,来更加直观地看一下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>
那么接下来我们再定义一个布局文件,给它取名为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>
- 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);
- }
- }
现在可以运行一下程序,结果如下图所示:
Button在界面上显示出来了!说明我们确实是借助LayoutInflater成功将button_layout这个布局添加到LinearLayout中了。LayoutInflater技术广泛应用于需要动态添加View的时候,比如在ScrollView和ListView中,经常都可以看到LayoutInflater的身影。
比较细心的朋友也许会注意到,inflate()方法还有个接收三个参数的方法重载,结构如下:
- inflate(int resource, ViewGroup root, boolean attachToRoot)
1. 如果root为null,attachToRoot将失去作用,设置任何值都没有意义。
2. 如果root不为null,attachToRoot设为true,则会在加载的布局文件的最外层再嵌套一层root布局。
3. 如果root不为null,attachToRoot设为false,则root参数失去作用。
4. 在不设置attachToRoot参数的情况下,如果root不为null,attachToRoot参数默认为true。
本文详细介绍了LayoutInflater的基本用法及其在Android中的应用场景。通过一个简单的例子展示了如何使用LayoutInflater动态加载布局,并将其添加到现有布局中。
194

被折叠的 条评论
为什么被折叠?



