Thursday, 12 December 2013

Dealing with back button by Implementing onBackPressed() (Updated with androidx package)


For exiting an application you may have noticed that not every app has a close button inside and therefore the hardware's back button is pressed to get away.

So now we will be using hardware's back functionality in order to get user's confirmation for exiting.
If user presses on "No" then, only the dialog disappears and the Activity does not exits otherwise the app will terminate which is usual.

Please Note: Here you must not call the parent activity's onBackPressed() method.


-----------------No extra xml editing, only the Java code will do-----------------------
package com.app.yourappname;

import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

public class BackButtonDealerActivity extends AppCompatActivity {

@Override
public void onCreate(Bundle b) {
super.onCreate(b);
}

@Override
public void onBackPressed() {
AlertDialog.Builder b = new AlertDialog.Builder(this)
.setTitle("Alert!")
.setCancelable(false)
.setMessage("Do you really want to close the app?")
.setIcon(R.mipmap.ic_launcher)
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(BackButtonDealerActivity.this, "'No' button was pressed...", Toast.LENGTH_LONG).show();
dialog.dismiss();
}
}).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
BackButtonDealerActivity.this.finish();
Toast.makeText(BackButtonDealerActivity.this, "'Yes' button was pressed...", Toast.LENGTH_LONG).show();
dialog.dismiss();
}
});
b.show();
}
}
----------------------------------------------------------------------------------------

-------------------------- Declare the Activity name in the manifest file -------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.app.yourappname">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".BackButtonDealerActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>
----------------------------------------------------------------------------------------


No comments:

Post a Comment