我已经研究过这个问题,参考LayoutInflater 文档 http://developer.android.com/reference/android/view/LayoutInflater.html并建立小样本示范项目。以下教程展示了如何使用动态填充布局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" />
Now 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
不指定 root 会导致 inflate 调用忽略 XML 中的布局参数。调用 inflate 时 root 不等于null
and attachRoot=true
确实加载布局参数,但再次返回根对象,这会阻止对加载的对象进行进一步的布局更改(除非您可以使用findViewById()
)。
因此,您最可能想要使用的调用约定是:
loadedView = LayoutInflater.from(context)
.inflate(R.layout.layout_to_load, parent, false);
为了帮助解决布局问题,布局检查器 https://developer.android.com/studio/debug/layout-inspector强烈推荐。