How to catch event with hardware back button on android?

前端 未结 3 1863
谎友^
谎友^ 2020-12-29 18:40

How to catch event with hardware back button on android ? I need to supress user to go back and I when click on back button on phone to show message and not to go on previou

相关标签:
3条回答
  • 2020-12-29 19:27

    you can do by this

    1. override the onBackPressed() method into your Activity like this way

      public void onBackPressed(){
           // do something here and don't write super.onBackPressed()
      }
      
    2. override the onKeyDown() method

      @Override
      public boolean onKeyDown(int keyCode, KeyEvent event) {
          switch(keyCode){
          case KeyEvent.KEYCODE_BACK:
              // do something here 
              return true;
          }
          return super.onKeyDown(keyCode, event);
      }
      
    0 讨论(0)
  • 2020-12-29 19:28

    You can suppress user "back" action with onKeyDown() in your activity like this:

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if ((keyCode == KeyEvent.KEYCODE_BACK))
        {
            //do actions like show message
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
    
    0 讨论(0)
  • 2020-12-29 19:34

    Override the method onBackPressed() in whatever Activity you want to create a different behaviour to the back button.

    These question are equal to yours (and could have been found by a simple search):

    how to disable back button in android

    Disable back button in android

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