我已经调查过这个问题,指的是LayoutInflater文档并建立了一个小样本示范项目。下面的教程演示如何使用LayoutInflater.
在我们开始之前看看LayoutInflater.inflate()参数看起来如下:资源*要加载XML布局资源的ID(例如,
R.layout.main_page)
根部*可选视图是生成的层次结构的父视图(如果
attachToRoot是
true),或者只是提供了一组
LayoutParams返回层次结构的根的值(如果
attachToRoot是
false.)
阿塔奇根:是否应将膨胀的层次结构附加到根参数?如果为false,根只用于创建正确的LayoutParams用于XML中的根视图。
回报膨胀的层次结构的根视图。如果根被提供并且attachToRoot是true,否则它就是膨胀的XML文件的根。
现在是示例布局和代码。
主要布局(main.xml):<?xml version="1.0" encoding="utf-8"?>
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
添加到这个容器中的是一个单独的TextView,如果从XML成功地应用了布局参数,它可以作为小红方可见(red.xml):<?xml version="1.0" encoding="utf-8"?>
android:layout_width="25dp"
android:layout_height="25dp"
android:background="#ff0000"
android:text="red" />
现在LayoutInflater用于多种不同的调用参数。public class InflaterTest extends Activity {
private View view;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ViewGroup parent = (ViewGroup) findViewById(R.id.container);
// result: layout_height=wrap_content layout_width=match_parent
view = LayoutInflater.from(this).inflate(R.layout.red, null);
parent.addView(view);
// result: layout_height=100 layout_width=100
view = LayoutInflater.from(this).inflate(R.layout.red, null);
parent.addView(view, 100, 100);
// result: layout_height=25dp layout_width=25dp
// view=textView due to attachRoot=false
view = LayoutInflater.from(this).inflate(R.layout.red, parent, false);
parent.addView(view);
// result: layout_height=25dp layout_width=25dp
// parent.addView not necessary as this is already done by attachRoot=true
// view=root due to parent supplied as hierarchy root and attachRoot=true
view = LayoutInflater.from(this).inflate(R.layout.red, parent, true);
}}
代码中记录了参数变化的实际结果。
摘要:呼叫LayoutInflater如果不指定根,就会导致调用膨胀,忽略XML中的布局参数。用根不相等调用充气null和attachRoot=true加载布局参数,但再次返回根对象,这将防止对加载对象进行进一步布局更改(除非您可以使用findViewById())。因此,您最想使用的调用约定是:loadedView = LayoutInflater.from(context)
.inflate(R.layout.layout_to_load, parent, false);
若要帮助解决布局问题,请将布局检查器强烈推荐。