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

后端 未结 10 1165
粉色の甜心
粉色の甜心 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: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();
            }
        }    
    }
    

提交回复
热议问题