Android - How To Override the “Back” button so it doesn't Finish() my Activity?

后端 未结 10 1138
粉色の甜心
粉色の甜心 2020-11-22 08:07

I currently have an Activity that when it gets displayed a Notification will also get displayed in the Notification bar.

This is so that when the User presses home a

相关标签:
10条回答
  • 2020-11-22 08:48

    simply do this..

    @Override
    public void onBackPressed() {
        //super.onBackPressed();
    }
    

    commenting out the //super.onBackPressed(); will do the trick

    0 讨论(0)
  • 2020-11-22 08:48

    Try this:

    @Override
    public void onBackPressed() {
        finish();
    }
    
    0 讨论(0)
  • 2020-11-22 08:50

    Just in case you want to handle the behaviour of the back button (at the bottom of the phone) and the home button (the one to the left of the action bar), this custom activity I'm using in my project may help you.

    import android.os.Bundle;
    import android.support.v7.app.ActionBar;
    import android.support.v7.app.AppCompatActivity;
    import android.view.MenuItem;
    
    /**
     * Activity where the home action bar button behaves like back by default
     */
    public class BackActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setupHomeButton();
        }
    
        private void setupHomeButton() {
            final ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) {
                actionBar.setDisplayHomeAsUpEnabled(true);
                actionBar.setHomeButtonEnabled(true);
            }
        }
    
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
                case android.R.id.home:
                    onMenuHomePressed();
                    return true;
            }
            return super.onOptionsItemSelected(item);
        }
    
        protected void onMenuHomePressed() {
            onBackPressed();
        }
    }
    

    Example of use in your activity:

    public class SomeActivity extends BackActivity {
    
        // ....
    
        @Override
        public void onBackPressed()
        {
            // Example of logic
            if ( yourConditionToOverride ) {
                // ... do your logic ...
            } else {
                super.onBackPressed();
            }
        }    
    }
    
    0 讨论(0)
  • 2020-11-22 08:50

    Looks like im very late but for those of you who need to switch to new screen and clear back button stack here is a very simple solution.

    startActivity(new Intent(this,your-new-screen.class));
    finishAffinity();
    

    The finishAffinity(); method clears back button stack.

    0 讨论(0)
提交回复
热议问题