开发者

Alert Dialog with custom layout failing

开发者 https://www.devze.com 2022-12-28 15:04 出处:网络
So this is related to a question I asked earlier. I am trying to display an alert using a specified layout. My layout is:

So this is related to a question I asked earlier. I am trying to display an alert using a specified layout. My layout is:

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

And the code to call and show the alert dialog is:

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

When I run it I get an error saying:

Uncaught handler: thread main exiting due to uncaught exception android.view.WindowManager$NadTokenException: Unable to add window -- token null is not for an application

I've looked t开发者_运维知识库hrough the android development site and can't figure it out. I think I'm just missing something obvious but the fix isn't jumping out at me. How can I get this alert dialog to display?


Do not use getApplicationContext(). That method is only available on a Context (e.g., Activity) -- use that Context for your AlertDialog.Builder.

Here is a sample project from one of my books that, among other things, shows an AlertDialog based off of a custom View.

0

精彩评论

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