开发者

Problem with AlertDialog

I'm having problem with creating AlertDialog.

I would like that AlertDialog appears when i click on one button, so i put all code for creating dialog in that button listener...the same code works outside that listener but inside listener doesn't work...it doesn't call any errors but when i start emulator written is something about this: "Aplication has terminated unexpectedly"....

This is my code for that:

btsenddata.setOnClickListener(new Button.OnClickListener() { 

      public void onClick (View v){ 

        AlertDialog.Builder alt_bld = new AlertDialog.Builder(getApplicationContext() ); // I've tried with "activity1.this" instead "getApplicationContext()" but it is the same result
        alt_bld.setMessage("Do you want to close this window ?")
        .setCancelable(false)
        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
        // Action for 'Yes' Button
        }
        })
        .setNegativeButton("No", new DialogInterface.OnCl开发者_C百科ickListener() {
        public void onClick(DialogInterface dialog, int id) {
        //  Action for 'NO' Button
        dialog.cancel();
        }
        });
        AlertDialog alert = alt_bld.create();
        // Title for AlertDialog
        alert.setTitle("Title");
        // Icon for AlertDialog
        alert.setIcon(R.drawable.icon);
        alert.show();
      }});
}

.... i've heard that method getApplicationContext() is creating some problems but i've tried replace it with activity.this and it doesn't work anyway... If anyone knows the reason for this or more about alertdialogs pleade answer. Thanks.


"Aplication has terminated unexpectedly"

Probably means you've got a stacktrace to view in LogCat that tells you the line number of the error. Look at that stack trace. If you can't understand it, post it here by editing your original question.


I have run your code and using MyActivity.this works. And what you want is, most of the time, the Activity context. See this blog post

You can also try with v.getContext()

AlertDialog.Builder alt_bld = new AlertDialog.Builder(v.getContext());


as in your code, you are implementing OnClickListener, which is not part of main activity,

to handle UI from any Listener, you need to create Handler.

public Handler mHandler = new Handler();

write above code in member declaration then,

mHandler.post(new Runnable() {
      public void run() {
            // your UI handling code
      }
});

write above code in Listener. This may solve you problem.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜