我很难像预期的那样工作,其他人也是:How to use layoutinflator to add views at runtime?人.
为什么LayoutInflater忽略我指定的布局参数?例如,为什么我的资源XML中的layout_width
和layout_height
值不受欢迎?
我很难像预期的那样工作,其他人也是:How to use layoutinflator to add views at runtime?人.
为什么LayoutInflater忽略我指定的布局参数?例如,为什么我的资源XML中的layout_width
和layout_height
值不受欢迎?
我已经调查了这个问题,参考了LayoutInflater docs并建立了一个小样本示范项目.以下教程演示了如何使用LayoutInflater
动态填充布局.
在我们开始之前,先看看LayoutInflater.inflate()
个参数是什么样子:
R.layout.main_page
)attachToRoot
是true
),或者只是一个为返回的层次 struct 的根提供一组LayoutParams
个值的对象(如果attachToRoot
是false
).attachToRoot:是否应将inflating 的层次 struct 附加到根参数?如果为false,则root仅用于为XML中的根视图创建正确的子类LayoutParams
.
Returns:inflating 层次 struct 的根视图.如果提供了root,attachToRoot
是true
,这就是root;否则它就是inflating 的XML文件的根.
现在查看示例布局和代码.
主要布局(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>
该容器中添加了一个单独的文本视图,如果从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);
}
}
参数变化的实际结果记录在代码中.
SYNOPSIS:在不指定根的情况下调用LayoutInflater
会导致忽略XML中的布局参数的inflating 调用.在root不等于null
和attachRoot=true
的情况下调用ifate确实会加载布局参数,但会再次返回根对象,从而防止对加载的对象进行进一步的布局更改(除非您可以使用findViewById()
找到它).
因此,您最可能使用的调用约定是:
loadedView = LayoutInflater.from(context)
.inflate(R.layout.layout_to_load, parent, false);
为了帮助解决布局问题,强烈建议使用Layout Inspector.