-> We will use the default hello world application, if the back button is pressed then there will be a dialog box displayed whether to close the application.
What we will need ?
- Dialog Box
- Changes in MainActivity.java
Step 2 : Give a name to your application (ExitPrompt) and package name as (com.mia.exitprompt). Click Next continuously.
Click Finish.
Step 3 : Open MainActivity.java from src->com.mia.exitprompt.
MainActivity.java
package com.mia.exitprompt;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onBackPressed(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
finish();
}
});
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
Step 4 : Run the application. Press the Back button after the application is started.
Explanation of the code :
- We have prepared an AlertBox. Using the setMessage() method we set the text to be displayed in the alert.
- setCancelable(false) is used to tell the compiler that the alert box is not exited implicitly.
- The positive button (yes) is used to exit the application by using finish() method.
- The negative button (no) is used to be in the same activity by doing nothing inside it.
Stay Tuned with Made In Android












No comments:
Post a Comment