0
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    LayoutInflater inflater = getLayoutInflater();
    LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.main, (ViewGroup) findViewById(R.id.root));

    Toast toast = new Toast(getApplicationContext());
    toast.setView(layout);
    toast.setDuration(2000);
    toast.show();
}

This code throws an java.lang.IllegalArgumentException: View not attached to window manager. If i change the line

LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.main, (ViewGroup) findViewById(R.id.root));

to

LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.main, null);

works just fine.

Can someone explain me why this happening? I'm new to Android platform and i'm just trying to understand how views and windows manager works. Don't understand why if the root view was attached to Activity cannot be used anymore to a toast view.

Any help is appreciated!

Thanks!

Viorel
  • 1
  • 1
  • 1
  • See this thread for an explanation of the difference between the application context and activity context http://stackoverflow.com/questions/4128589/difference-between-activity-context-and-application-context – ccheneson Apr 10 '11 at 16:06
  • that doesn't answer to my question. Thanks! – Viorel Apr 11 '11 at 04:00
  • Come on! Nobody can give me a hint?? – Viorel Apr 12 '11 at 11:52

2 Answers2

2

When you make a call to inflater.inflate, the root parameter is optional, and is supposed to be a parent of the layout you're trying to inflate (for example when you're trying to inflate the view for a single row in a list view, you give the list view as the parent).

My guess is that in your code, R.layout.main does not have any parent ? In that case the parent is supposed to be null.

Abhinav Manchanda
  • 6,546
  • 3
  • 39
  • 46
1

Don't attach the inflated layout to root. Call inflate with 3 params, last one false:

LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.main, (ViewGroup) findViewById(R.id.root), false);
Pahomi
  • 455
  • 6
  • 17