Greetings Stack Overflow Community
When creating a custom Toast the android developer guide as well as this stack overflow post, both provide the following example:
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();
A Few Notes
If the second argument is null, then inflate()
should return the root of the xml file, which is the LinearLayout called toast_container
.
Otherwise, if a ViewGroup is passed as the second argument, then inflate()
should attach the inflated hierarchy to this ViewGroup and return the provided ViewGroup (which is now the parent of the inflated layout).
I have 2 questions:
First:
What is the purpose of providing a second argument? By default, the LinearLayout with the id @+id/toast_container
will be returned if we pass null.
Second:
How can the inflated hierarchy be inflated (and embedded) to one of its own members? Or, is the above usage of inflate() considered improper?
In other words, this code is inflating (and embedding) the layout into one of its own members, that is the LinearLayout (check @+id/toast_container
).
This duplicates the LinearLayout by inflating the xml file into a second LinearLayout.