自定义布局的警告对话框失败

4
所以这与我之前提出的问题有关。我正在尝试使用指定的布局来显示警报。我的布局是:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/layout_root"
              android:orientation="horizontal"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:padding="10dp">
    <TextView android:id="@+id/text"
              android:layout_width="wrap_content"
              android:layout_height="fill_parent"
              android:textColor="#FFF" />   
</LinearLayout>

调用并显示警告对话框的代码如下:

    Context mContext = getApplicationContext();

    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
    // use a custom View defined in xml
    View view = LayoutInflater.from(mContext).inflate(R.layout.sell_dialog,      (ViewGroup) findViewById(R.id.layout_root));
    builder.setView(view);
    builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

            // do whatever you want with the input
        }
    });
    AlertDialog alertDialog = builder.create();

    alertDialog.show();

当我运行它时,出现以下错误:

未捕获的 handler: 主线程由于未捕获的异常而退出 android.view.WindowManager$NadTokenException: 无法添加窗口 -- token null 不是应用程序

我已经查看了 Android 开发网站,但仍然无法解决。我认为我可能只是忽略了一些显而易见的问题,但是修复方法并不明显。如何让这个警告对话框显示出来?

1个回答

9
不要使用getApplicationContext()方法。该方法仅适用于Context(例如Activity) - 请使用该Context来构建您的AlertDialog.Builder
以下是我书中的一个示例项目,其中包括一个基于自定义ViewAlertDialog点击这里查看

我对使用自定义视图的警报对话框示例很感兴趣,但是您提供的链接中没有这样的示例。 - Nemi
@Nemi:哎呀,你说得对。对不起。试试这个链接:http://github.com/commonsguy/cwac-colormixer - CommonsWare
谢谢。我正在尝试创建一个带有自定义视图并使用setMessage()字符串的AlertDialog,但是我发现如果消息字符串足够长以调用内部listView中的滚动条,则布局会出错。我希望您的示例能提供一些见解,但看起来我可能需要编写完整的自定义对话框。 - Nemi
谢谢,我使用了您在ConstantsBrowser.java中的示例,它非常好用。我不知道为什么他们不更新Android对话框信息页面,原帖作者就是从那里获取示例的。我也遇到了完全相同的问题,尝试在ExpandableListActivity类中构建自定义布局的Alert Dialog Builder。祝好! - Sean A.O. Harney

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