onBackPressed() method not triggered in AppCompatActivity

前端 未结 6 867
囚心锁ツ
囚心锁ツ 2021-02-13 23:26

AppCompatActivity onBackPressed() method fails to trigger in my activity.

I see the back arrow button and get the animation when pressing it, but nothing else happens. a

6条回答
  •  后悔当初
    2021-02-14 00:13

    This code works for me. Obviously there isn't all the code, but i think it can usefull for you to understand how to implements the backPressed event.

    public class RedActivity extends AppCompatActivity {
    
      @Override
      protected void onCreate(Bundle savedInstanceState) {
        ...
        final ActionBar ab = getSupportActionBar();
        ab.setHomeAsUpIndicator(R.drawable.ic_menu);
        ab.setDisplayHomeAsUpEnabled(true);
        ...
      }
    
      ...
    
      @Override
      public void onBackPressed() {
        if (isDrawerOpen()) {
          drawerLayout.closeDrawer(GravityCompat.START);
        } else if (getFragmentManager().getBackStackEntryCount() > 0) {
          getFragmentManager().popBackStack();
        } else {
         //Ask the user if they want to quit
         new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert)
                            .setTitle(R.string.quit)
                            .setMessage(R.string.really_quit)
                            .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
    
                                @Override
                                public void onClick(DialogInterface dialog, int which) {        
                                    finish();
                                }
    
                            })
              .setNegativeButton(R.string.no, null)
              .show();
           }
        }
    }
    

提交回复
热议问题