how to disable back button in android [duplicate]

2019-01-19 11:20发布

问题:

This question already has an answer here:

  • Disable back button in android 14 answers

i am making swap application... i want to disable back button. so i use this code... and passed intent in to it..

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
        // do something on back.
        return true;
    }

    return super.onKeyDown(keyCode, event);
}

but while running when i press back button on emulator it updates activity but when i repress back button it switch to the home page of an emulator.. please suggest is their any other method

回答1:

@Override
public void onBackPressed() {
    // do nothing.
}


回答2:

    @Override
        public void onBackPressed() {
            //super.onBackPressed();
            if(SOME_CONDITION_TO_CHECK){
                //THIS BLOCK WILL NOT DO ANYTHING AND WOULD DISABLE BACK BUTTON

            }else{
                super.onBackPressed();
//THIS BLOCK WILL BE CALLED IF ABOVE COND IS FALSE, AND WOULD ENABLE BACK BUTTON
            }

        }


回答3:

Did you try onBackPressed() ?

@Override
public void onBackPressed() {
       // Do as you please
}


回答4:

This is my solution it works using Android 2.2

override onBackPressed() ...

public void onBackPressed() {
   // check if you are in the right mode 
   if (getCurrentState() == FORM_STATE_BROWSE ) {
       // ok do default back action
       super.onBackPressed();
   }

   // exit skipping "onBackPressed()"
   return;
}


回答5:

You must add return in order for this to sucessfully work on all devices, my note 3 & htc still go back if I don't include return!

  @Override
        public void onBackPressed() {
             return;
        }


回答6:

Like if you want to move on some activity by pressing back button,override this method in your activity

 @Override
    public void onBackPressed() {
        // do nothing.
        Intent intent = new Intent(SocialPlugIns.this, MainActivity.class);
        Log.i("Hello", "This is Coomon Log");
        startActivity(intent);
           return;
    }


回答7:

You have to override onBackPressed() function. Below I am giving a way:

   @Override
    public void onBackPressed() {
       //make some alert for the user
    }