【问题标题】:Alert Dialog with custom layout failing自定义布局失败的警报对话框
【发布时间】:2012-01-04 06:53:13
【问题描述】:

所以这与我之前提出的一个问题有关。我正在尝试使用指定的布局显示警报。我的布局是:

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

当我运行它时,我收到一条错误消息:

未捕获的处理程序:线程主因未捕获的异常而退出 android.view.WindowManager$NadTokenException: 无法添加窗口 -- 令牌 null 不适用于应用程序

我浏览了 android 开发网站,但无法弄清楚。我想我只是错过了一些明显的东西,但修复并没有跳出来。如何显示此警报对话框?

【问题讨论】:

    标签: android


    【解决方案1】:

    不要使用getApplicationContext()。该方法仅适用于Context(例如Activity)——将Context 用于您的AlertDialog.Builder

    Here is a sample project 来自我的一本书,其中显示了基于自定义 ViewAlertDialog

    【讨论】:

    • 工作就像一个魅力。非常感谢!
    • 我对使用自定义视图的警报对话框的示例感兴趣,但是您的链接没有这样的示例。
    • @Nemi:哎呀,你是对的。对于那个很抱歉。试试这个:github.com/commonsguy/cwac-colormixer
    • 谢谢。我正在尝试使用自定义视图创建一个 AlertDialog 并使用 setMessage() 字符串,但我发现如果消息字符串足够长以调用内部 listView 中的滚动条,那么布局就会搞砸。我希望您的示例能够提供一些见解,但看起来我可能需要编写一个完整的自定义对话框。
    • 谢谢,我使用了 ConstantsBrowser.java 中的示例,效果很好。我不知道他们为什么不更新原始海报获得示例的 Android Dialogs Information 页面。我在尝试在 ExpandableListActivity 类中执行自定义布局警报对话框生成器时遇到了完全相同的问题。干杯!
    猜你喜欢
    • 2014-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多