我在使LayoutInflater按预期工作时遇到了严重问题,其他人也是如此:How to use layoutinflator to add views at runtime?。
为什么LayoutInflater会忽略我指定的布局参数?例如。为什么我的资源XML中的layout_width
和layout_height
值不受尊重?
答案 0 :(得分:366)
我已经调查了这个问题,参考了LayoutInflater docs并设置了一个小样本演示项目。以下教程介绍了如何使用LayoutInflater
动态填充布局。
在我们开始之前,请看看LayoutInflater.inflate()
参数是什么样的:
R.layout.main_page
)attachToRoot
是true
),或者只是提供一组{{1}的对象返回层次结构的根值(如果LayoutParams
为attachToRoot
。) attachToRoot :是否应将膨胀的层次结构附加到根参数?如果为false,则root仅用于为XML中的根视图创建false
的正确子类。
返回:膨胀层次结构的根视图。如果提供了root并且LayoutParams
是attachToRoot
,则这是root;否则它是膨胀的XML文件的根。
现在为样本布局和代码。
主要布局(true
):
main.xml
在此容器中添加了一个单独的TextView,如果从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>
)成功应用布局参数,则可视为小红色方块:
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);
}
}
来强制调用忽略XML中的布局参数。使用不等于LayoutInflater
和null
的root调用inflate会加载布局参数,但会再次返回根对象,这会阻止对已加载对象进行进一步的布局更改(除非您可以使用{{1}找到它})。
因此,您最有可能想要使用的调用约定是:
attachRoot=true
为了解决布局问题,强烈建议使用Layout Inspector。
答案 1 :(得分:4)
andig是正确的,LayoutInflater忽略layout_params的一个常见原因是因为没有指定root。很多人认为你可以为root传入null。对于诸如对话之类的几种情况,这是可以接受的,在对话中,您在创建时无权访问root。但是,遵循的一个好规则是,如果你有root,请将它交给LayoutInflater。
我写了一篇关于此的深度博客文章,你可以在这里查看:
https://www.bignerdranch.com/blog/understanding-androids-layoutinflater-inflate/
答案 2 :(得分:0)
想添加到上面的主要答案中
我尝试遵循它,但是我的recyclerView开始将每个项目拉伸到屏幕上
充气后我必须添加下一行才能达到目标
itemLayoutView.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT));
我已经通过xml添加了这些参数,但无法正常工作
并在这行一切正常