使用LayoutInflater.inflate()来创建的Android
问候定制吐司堆栈溢出社区使用LayoutInflater.inflate()来创建的Android
在创建自定义敬酒android developer guide以及本stack overflow post,都提供了下面的例子:
my_custom_toast。 XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toast_container"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ImageView android:src="@drawable/droid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
MainActivity.java
个LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(
R.layout.my_custom_toast,
(ViewGroup) findViewById(R.id.toast_container)
);
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("This is a custom toast");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
的几点注意事项
如果第二个参数为空,则inflate()
应该返回xml文件,这是的LinearLayout称为toast_container
的根。 否则,如果ViewGroup作为第二个参数传递,那么inflate()
应该将膨胀的层次结构附加到此ViewGroup并返回提供的ViewGroup(它现在是充气布局的父级)。
我有2个问题:
第一:
什么是提供第二个参数的目的是什么?默认情况下,如果我们传递null,将返回标识为@+id/toast_container
的LinearLayout。
二:
如何膨胀的层次充气(嵌入式),以自己的成员之一吗?或者,inflate()的上述用法是否被认为是不恰当的?
换句话说,此代码正在将布局膨胀(并嵌入)到其自己的成员之一中,即LinearLayout(检查@+id/toast_container
)。 这通过将xml文件充入第二个LinearLayout来复制LinearLayout。
回答你的第一个问题,视图的膨胀将使用第二个参数,以便正确执行几个步骤。主要与LayoutParams类有关(许多视图类有一个对应的LayoutParams类)。如果您尝试使用边距,这些可能仅在您传递第二个参数时才有效。
问题2:您误解了文档。如果你传递了第二个参数ViewGroup,我将其称为'parent',你的布局将被膨胀到'parent'并且函数返回'parent'。
在您没有通过第二个参数的情况下,功能膨胀你的布局,将返回布局本身(根/顶视图)。
关于问题2:**我完全同意你说的**。但是,如果第二个参数的唯一目的是推断ViewGroup.LayoutParams的类型,那么他们应该使用'inflate(R.layout.xml_file,ViewGroup,false)'。这样就可以推断出LayoutParams类型(根据文档)。我的问题是,他们膨胀(和嵌入)膨胀的布局到其自己的成员之一,这是线性布局(检查@ + id/toast_container)。他们通过将xml文件充入第二个LinearLayout来复制linearlayout。这就是问题2的意思。 – Maged
这里是我提到的文档。 https://developer.android.com/reference/android/view/LayoutInflater.html#inflate%28int%2C%20android.view.ViewGroup%2C%20boolean%29 – Maged
作为本网站规范的一部分,请避免在每篇文章中提出多个问题,因为这会使回答和投票更加棘手。 –