Thursday 5 September 2013

Back Button Coding Demo

Demo:

1) MainActivity.java:
 
package com.venky.backbuttondemo;
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);
       }

       @Override
       public void onBackPressed() {
             displayDialog();
       }

       public void displayDialog() {

             AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
             alert.setMessage("Are you sure to leave this App");

             alert.setNegativeButton("Cancel",
                           new DialogInterface.OnClickListener() {

                                 @Override
                                 public void onClick(DialogInterface dialog, int pos) {
                                        dialog.cancel();
                                 }
                           });

             alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int pos) {
                           finish();
                    }
             });

             alert.show();
       }
}

2) activity_main.xml: 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#5F04B4"
    android:orientation="vertical" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:gravity="center"
        android:text="Back Button Behavior Chenged"
        android:textColor="#ffffff"
        android:textSize="18dp"
        android:textStyle="bold" />

</LinearLayout>

3) Download this Project Click Here

No comments:

Post a Comment