Sunday, 28 August 2016

Exit Button in Android Studio

Exit Button is used when you exit the application. Means You play game or learn any tutorial. You make some rest so you exit the app. In Exit button show notification You want to really exit or not. If user click no you do not exit the app or game. If you click yes you exit the app or a game.
Firstly Create new project No any changing in activitymain.xml or AndroidManifest.xml only few line added in MainActivity.java See this example
MainActivity.java


package com.jkssafaltips.app.one.in.all.myapplication;

import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override 
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    @Override 
 public void onBackPressed() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(false);
        builder.setMessage("Are you sure you want to Exit?");
        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override 
 public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override 
 public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        AlertDialog alert = builder.create();
        alert.show();
    }
}
You also see my other posts directly this link
Click Button and Open New Activity 
Custom Toast Example 
 

No comments:

Post a Comment