LayoutInflater中Inflater方法的学习
在初学Android过程中,我对LayoutInflater的Inflater方法的参数产生了困惑,这个函数到底做了什么呢?在网上查阅了大量文档后还是一脸懵逼。今天从_江南一点雨的博客学习到了Inflater方法中的各参数意义。这篇博客主要是为了记录并总结概述参数不同情况下Inflater所表现出含义的解释。
三个参数的Inflater方法
函数原型
public View inflate(int resource, ViewGroup root, boolean attachToRoot)
三个参数的Inflater可能会有三种情况,借此我们分开讨论。
- root不为NULL,attachToRoot为True
将控件加入到root这个容器中 - root不为NULL,attachToRoot为false
root会协助控件根节点生成布局参数 - root为NULL,attachToRoot任意
由于控件不属于任何容器,所以其宽、高属性均会失效
举个例子(原博主的例子):
Activity的布局如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/ll"
tools:context="org.sang.layoutinflater.MainActivity">
</LinearLayout>
自定义布局linearlayout.xml如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ll"
android:layout_width="200dp"
android:layout_height="200dp"
android:background="@color/colorPrimary"
android:gravity="center"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
第一种情况:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
LayoutInflater inflater = LayoutInflater.from(this);
inflater.inflate(R.layout.linearlayout, ll,true);
}
效果:
第二种情况:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.linearlayout, ll, false);
ll.addView(view);
}
效果:与前者一样(注意与第三种情况对比)
第三种情况:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.linearlayout, null, false);
ll.addView(view);
}
效果:
我们可以明显发现,他的宽度与高度均失效,是由于这个控件不存在与任何容器中。如果修改button,则button会立即有变化,因为button是处于某一个容器中的。
两个参数的Inflater方法
函数原型
public View inflate(int resource, ViewGroup root) {
return inflate(resource, root, root != null);
}
看到函数原型就很好解释了,他只不过将两个参数的Inflater转换为三个参数的。
- root为空
如同三个参数的第三种情况。 - root不为空
如同三个参数的第一种情况。