onbackpressed使我的应用程序关闭,没有确认

时间:2015-08-02 20:38:10

标签: android pressed onbackpressed

我是新的Android开发人员,当我从菜单中的任何页面按回来时,我的应用程序关闭。我在对话框中添加了这段代码,但它无法正常工作

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

    FragmentManager fm = getSupportFragmentManager();
    int count = fm.getBackStackEntryCount();

    if(count == 0) {
        // Do you want to close app?
    }

}

3 个答案:

答案 0 :(得分:1)

您是否尝试将KEYCODE_BACK调用放入else块中,以便仅在密钥不是/* Prevent app from being killed on back */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // Back? if (keyCode == KeyEvent.KEYCODE_BACK) { // Back moveTaskToBack(true); return true; } else { // Return return super.onKeyDown(keyCode, event); } } 时调用?

{{1}}

这应该适用于现在!如果您有任何问题,请随时发表评论。

答案 1 :(得分:0)

试试这个:

@Override
public void onBackPressed() {
    FragmentManager fm = getSupportFragmentManager();
    int count = fm.getBackStackEntryCount();
    if(count == 0) {
       // Do you want to close app?
       showDialog();
    }
}

public void showDialog() {
    AlertDialog.Builder alert = new AlertDialog.Builder(this);
    alert.setTitle("Do you want to close the app");
    alert.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
              finish();  //or super.onBackPressed();
        }
    });
    alert.setNegativeButton("Dismiss", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
        }
    });
    alert.show();
}

答案 2 :(得分:0)

使用以下内容覆盖活动的onBackPressed,以防您在某些值中进行了更改,但之后忘记更新它们,而是按下后退按钮:

@Override
  public void onBackPressed() {
    if( <condition>) {
      AlertDialog.Builder ad = new AlertDialog.Builder( this);
      ad.setTitle("Changes were made. Do you want to exit without update?");
      ad.setPositiveButton(
              "OK",
              new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                  backPress();
                }
              }
      );
      ad.setNegativeButton(
              "Update the changes",
              new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                  <Update the changes>;
                  Toast.makeText(getApplicationContext(), "Changes were updated", Toast.LENGTH_SHORT).show();
                  backPress();
                }
              }
      );
      ad.setCancelable( false);
      ad.show();
    } else {
      backPress();
    }
  }

  private void backPress() {
    super.onBackPressed();
  }