activity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="180dp"
android:gravity="center_horizontal"
android:text="Press The Back Button of Your Phone."
android:textSize="30dp"
android:textStyle="bold" />
</RelativeLayout>
activity.java
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
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() {
// Create the object of AlertDialog Builder class
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
// Set the message show for the Alert time
builder.setMessage("Do you want to exit ?");
// Set Alert Title
builder.setTitle("Alert !");
// Set Cancelable false for when the user clicks on the outside the Dialog Box then it will remain show
builder.setCancelable(false);
// Set the positive button with yes name Lambda OnClickListener method is use of DialogInterface interface.
builder.setPositiveButton("Yes", (DialogInterface.OnClickListener) (dialog, which) -> {
// When the user click yes button then app will close
finish();
});
// Set the Negative button with No name Lambda OnClickListener method is use of DialogInterface interface.
builder.setNegativeButton("No", (DialogInterface.OnClickListener) (dialog, which) -> {
// If user click no then dialog box is canceled.
dialog.cancel();
});
// Create the Alert dialog
AlertDialog alertDialog = builder.create();
// Show the Alert Dialog box
alertDialog.show();
}
}
No comments:
Post a Comment