无法添加窗口--令牌null不属于应用程序

4

您好,我正在尝试从AsyncTask的onPostExecute()方法中膨胀一个视图(B.xml),该视图中包含一个下拉列表框,以便在MainActivity的视图(A.xml)中显示。

MainActivity.class

protected void onPostExecute(String result) {
        LayoutInflater vi = (LayoutInflater) getApplicationContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = vi.inflate(R.layout.B, null);
        branded_spinner = (Spinner) v.findViewById(R.id.Spinner01);

        adapter_branded = new ArrayAdapter<String>(**MainActivity.this**,
                android.R.layout.simple_spinner_item, Branded);
        adapter_branded.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        branded_spinner.setAdapter(adapter_branded);                        
        branded_spinner.setOnItemSelectedListener(**MainActivity.this**);

它在4.0及以上版本上运行良好,但对于2.3.3版本,我遇到了错误。

11-30 15:28:55.492: E/AndroidRuntime(540): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
11-30 15:28:55.492: E/AndroidRuntime(540):  at android.view.ViewRoot.setView(ViewRoot.java:531)
11-30 15:28:55.492: E/AndroidRuntime(540):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
11-30 15:28:55.492: E/AndroidRuntime(540):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)

我尝试使用getApplicationContext(),但仍然出现相同的错误。

我参考了以下链接:

Dialog throwing "Unable to add window — token null is not for an application” with getApplication() as context

Android: ProgressDialog.show() crashes with getApplicationContext

Android 1.6: "android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application"

这些链接可以帮助你解决相关问题。


当我点击下拉框时,出现错误。 - ashish.n
1
你确定你可以使用ApplicationContext来进行绘图吗?你尝试过通过LayoutInflater.from(context)静态构造函数获取LayoutInflater对象实例吗(其中context是你的活动的上下文)? - Evos
是的,所有的东西都在我给出的代码片段中。 - ashish.n
好的,尝试使用以下构造函数来创建你的 vi 变量:LayoutInflater vi = LayoutInflater.from(YourActivityName.this); - Evos
是的,它起作用了。谢谢Evos。我已经卡在这上面很长时间了... - ashish.n
没问题,我会把我的评论转换成答案,如果您能将其标记为答案就太好了。 - Evos
2个回答

6

好的,对于你的vi变量,尝试使用以下构造函数:LayoutInflater vi = LayoutInflater.from(YourActivityName.this);


0

你只需要传递 LayoutInflater.from(this);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接