I'm trying to start an AlertDialog from an onClickListener but I'm getting the following error.
The constructor AlertDialog.Builder(new View.OnClickListener(){}) is undefined
Does anyone know how to fix this?
mRecordButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new AlertDialog.Builder( this )
.setTitle( "Cast Recording" )
.setMessage( "Now recording your message" )
.setPositiveButton( "Save", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.d( "AlertDialog", "Positive" );
}
})
.setNegativeButton( "Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.d( "AlertDialog", "Negative" );
}
} )
.show();
}
});
In
new AlertDialog.Builder( this )
,this
is referring to the listener, not the outer class instance.Change this line
to
This is because the constructor needs a Context type &
OnclickListner is not a Context type
so you use the object of your Activity.I hope it helps..
Step 1. Create a file activity_main.xml
Step 2. Create a class MainActivity.java
Code online : AlertDialog onlick in android