Home > Net >  Handling backpress on activity
Handling backpress on activity

Time:11-24

I have 2 activity called Login and Main in login activity there is code block that makes this functionality that if I click back in Main activity it will close the app instead of going back to login activity but I want to handle back press and maybe with one dialog "you are going to exit the app you sure? " or something like this.

Intent intent = new Intent(LoginActivity.this, MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);

this code block is in my login actvity

CodePudding user response:

copy and paste the below code in your onBackPressed() method in MainActivity.java.

new AlertDialog.Builder(MainActivity.this)
            .setTitle("Confirm close")
            .setMessage("Are you sure want to close app")
            .setCancelable(false)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which {
                    finish();
                }
             }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog, int which {
                   dialog.dismiss();
                 }
             }).create().show();

CodePudding user response:

You can handle in onBackPressed if user is logged in :

override fun onBackPressed() {
        if(!user.isLoggedIn()){
            val intent = Intent(this@LoginActivity, MainActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
            startActivity(intent)
            finish()
        }else{
            //Show alert
        }
    }
  • Related