inflate(int resource, ViewGroup root, boolean attachToRoot) 有三个参数,第一个是layout资源id,第二个代表是否加载宽高参数,第三个代表是否加到view里去
root为null时,attachToRoot没有意义
举个例子,这是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="400dp"
android:layout_height="400dp"
android:text="Button" >
</Button>
核心代码是
public class MainActivity extends ActionBarActivity {
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, mainLayout,false);
mainLayout.addView(buttonLayout);
}
}
一般有三种用法,
View buttonLayout =layoutInflater.inflate(R.layout.button_layout, null);
mainLayout.addView(buttonLayout);
此时button渲染成功,但是button在xml里的宽高参数没有加上去
如何加?
可以在addView里面加,addview有public void addView(View child, int width, int height)形式的函数,可以送入宽高,但是我们相当于重新写了一遍宽高,没有用button_layout里面的宽高
想直接用button_layout里面的宽高,怎么办?inflate的时候初始化宽高值,只要设置了root,宽高值就会被初始化,为什么初始化宽高值要送入root呢?注意源码里有params = root.generateLayoutParams(attrs);这句话,你要是不知道root是什么,就连宽高的数据类型都无法确定, root是RelativeLayout,那么宽高参数就是RelativeLayout.LayoutParams,如果root是LinearLayout,那么宽高参数就是LinearLayout.LayoutParams.宽高参数准确的来说应该叫布局参数,这里不深究
改为
View buttonLayout =layoutInflater.inflate(R.layout.button_layout, mainLayout,false);
mainLayout.addView(buttonLayout);
达到目的,宽高值被初始化
还有一种方法,View buttonLayout =layoutInflater.inflate(R.layout.button_layout, mainLayout,true);
这句话跟上面2句话效果一样,
http://bxbxbai.github.io/2014/11/19/make-sense-of-layoutinflater/
http://blog.csdn.net/guolin_blog/article/details/12921889