开发者

View not attached to Window Manager

    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);

w开发者_JAVA百科orks 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!


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.


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜