我已经调查过这个问题,参考LayoutInflater docs 并设置了一个小样本演示项目。以下教程展示了如何使用 LayoutInflater 动态填充布局。
在我们开始之前,看看LayoutInflater.inflate() 参数是什么样的:
现在是示例布局和代码。
主布局(main.xml):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
添加到此容器中的是一个单独的 TextView,如果布局参数从 XML 成功应用,则显示为红色小方块 (red.xml):
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
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);
}
}
参数变化的实际结果记录在代码中。
概要: 在不指定 root 的情况下调用 LayoutInflater 会导致膨胀调用忽略 XML 中的布局参数。使用 root 不等于 null 和 attachRoot=true 调用 inflate 确实会加载布局参数,但会再次返回根对象,这会阻止对加载的对象进行进一步的布局更改(除非您可以使用 findViewById() 找到它)。
因此,您最有可能使用的调用约定是这个:
loadedView = LayoutInflater.from(context)
.inflate(R.layout.layout_to_load, parent, false);
为了帮助解决布局问题,强烈建议使用Layout Inspector。