v3rt1ag0
v3rt1ag0

Reputation: 824

Why should I use LayoutInflater to obtain a view if I can directly obtain it using findViewById()

I am a beginner in android development and am having a hard time understanding the use of Inflater.I have already read this question:

What does it mean to inflate a view from an xml file?

Now consider this example:

LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
                               (ViewGroup) findViewById(R.id.toast_layout_root));
Toast toast = new Toast(getApplicationContext());
toast.setView(layout);
toast.show();

From what I understood we used inflater to inflate(convert) the xml layout into a View object and then we set the view using setView(layout). But if we just had to set view of toast then why not simply use findviewbyid as follows:

Toast toast=new Toast(this);
toast.setView(findViewById(R.id.toast_layout_root));
toast.setDuration(toast.LENGTH_LONG);
toast.show();

The above code compiles but it causes the application to crash at start up.I know it is wrong to do it this way but why?

What will be the difference between the view obtained by using inflater and the view obtained using findViewById.

Upvotes: 2

Views: 235

Answers (1)

Nanoc
Nanoc

Reputation: 2381

Its not the same thing.

Inflate takes a Layout xml file and makes a View out of it.

findViewById looks for a view inside a viewGroup.

In your example:

Your first code will inflate R.layout.custom_toast and attach it to the parent ViewGroup R.id.toast_layout_root

Your second code will take the R.id.toast_layout_root ViewGroup and set it as the layout of the dialog.

Basically your first code will end up with R.layout.custom_toast as the dialog layout while your second code will use R.id.toast_layout_root as the dialog layout.

Its clearly not the same thing, findViewById needs an already inflated View.

Hope this helps.

Upvotes: 1

Related Questions