I'm trying to show an alert dialog when the user click a button

    Previous.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            AlertDialog.Builder answerAlert = new AlertDialog.Builder(this);
        }
    });

but I got an error in this line

            AlertDialog.Builder answerAlert = new AlertDialog.Builder(this);

which said

 The constructor AlertDialog.Builder(new View.OnClickListener(){}) is undefined

anyone know how to fix it? thanks

有帮助吗?

解决方案

AlertDialog gets Context in the Constructor but you used this inside your onClickListenner. Instead you should write YourActivity.this

 Previous.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View view) {
        AlertDialog.Builder answerAlert = new AlertDialog.Builder(YourActivity.this);
    }
 });

其他提示

this is your anonymous OnClickListener inner class. Use MyActivity.this instead (replace MyActivity with the name of the activity).

You have to pass an object of Context to the AlertDialog.Builder constructor and View.OnClickListener does not extend Context

Change

AlertDialog.Builder answerAlert = new AlertDialog.Builder(this);

to

AlertDialog.Builder answerAlert = new AlertDialog.Builder(YourActivity.this);

as Activity extends Context

In your code this is your View.OnClickListener interface implementation.

Try this :

AlertDialog.Builder answerAlert = new AlertDialog.Builder(YourActivity.this);

Where YourActivity is your Activity's name

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top