2

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.

Community
  • 1
  • 1
v3rt1ag0
  • 785
  • 1
  • 8
  • 22
  • 1
    Using an inflater creates a view programmatically, using findViewById grabs the view from the current window where it is already created and sized. – RobVoisey Nov 10 '15 at 15:47
  • 1
    I would expect both to crash, complaining that the `View` already has a parent. – CommonsWare Nov 10 '15 at 15:47

1 Answers1

1

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.

Nanoc
  • 2,381
  • 1
  • 20
  • 35