android - On back button pressed example

activity_main.xml
 <?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout     xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     android:id="@+id/coordinator_layout"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:background="#d1dece"     > </android.support.design.widget.CoordinatorLayout> 
MainActivity.java
 package com.cfsuman.me.androidcodesnippets;  import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.support.design.widget.CoordinatorLayout; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast;   public class MainActivity extends AppCompatActivity{     private Context mContext;     private Activity mActivity;      private CoordinatorLayout mCLayout;       @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          // Get the application context         mContext = getApplicationContext();         mActivity = MainActivity.this;          // Get the widget reference from XML layout         mCLayout = (CoordinatorLayout) findViewById(R.id.coordinator_layout);     }      @Override     public void onBackPressed(){         AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);          builder.setTitle("Please confirm");         builder.setMessage("Are you want to exit the app?");         builder.setCancelable(true);          builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {             @Override             public void onClick(DialogInterface dialogInterface, int i) {                 // Do something when user want to exit the app                 // Let allow the system to handle the event, such as exit the app                 MainActivity.super.onBackPressed();             }         });          builder.setNegativeButton("No", new DialogInterface.OnClickListener() {             @Override             public void onClick(DialogInterface dialogInterface, int i) {                 // Do something when want to stay in the app                 Toast.makeText(mContext,"thank you",Toast.LENGTH_LONG).show();             }         });          // Create the alert dialog using alert dialog builder         AlertDialog dialog = builder.create();          // Finally, display the dialog when user press back button         dialog.show();     } } 

Komentar