如何在android中禁用后退按钮

时间:2011-04-15 07:00:00

标签: android back-button

我正在制作交换应用程序...我想禁用后退按钮。所以我使用这段代码......并将意图传递给它..

@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);
}

但是在我按下模拟器上的按钮时运行它会更新活动但是当我按下后退按钮时它会切换到模拟器的主页..请建议是他们的任何其他方法

7 个答案:

答案 0 :(得分:62)

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

答案 1 :(得分:17)

 @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
    }   

 }

答案 2 :(得分:6)

你试过onBackPressed()吗?

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

答案 3 :(得分:3)

这是我的解决方案 它适用于Android 2.2

覆盖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;
}

答案 4 :(得分:2)

必须添加返回,以便在所有设备上成功运行,我的Note-3&如果我不包括退货,HTC仍然会回去!

  @Override
  public void onBackPressed() {
        return;
  }

答案 5 :(得分:1)

如果您想通过按后退按钮继续某些活动,请在活动中覆盖此方法

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

答案 6 :(得分:0)

您必须覆盖onBackPressed()功能。下面我给出了一个方法:

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