0

我是新的 android 开发人员,当我从菜单中的任何页面按下返回时,我的应用程序将关闭。我用对话框添加了这段代码,但它不起作用

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

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

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

}

4

3 回答 3

1

您是否尝试过将super调用放在 else 块中,以便仅在键不是时才调用它KEYCODE_BACK

/* 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);
        }
    }

现在应该可以了!如果您有任何问题,请随时发表评论。

于 2015-08-02T20:45:51.643 回答
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();
}
于 2015-08-02T21:36:05.133 回答
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();
  }
于 2016-04-24T18:41:46.470 回答