4

我正在覆盖活动中的 onBackPressed 方法:

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

我正在添加片段如下:

    fragmentManager.beginTransaction()
                .add(R.id.frame_container, myFragment).addToBackStack("").commit();

问题是我的 onBackPressed 没有在活动中被调用。但是当我将其更改为:

replace(R.id.frame_container, myFragment).addToBackStack("").commit();

它按预期被调用。我必须添加片段。如何解决这个问题?

4

2 回答 2

4
@Override
public boolean onKeyUp(int keyCode, KeyEvent objEvent) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        onBackPressed();
        return true;
    }
    return super.onKeyUp(keyCode, objEvent);
}

@Override
public void onBackPressed() {

    goBack();
}

public void goBack() {

    AlertDialog.Builder alertDialog = new AlertDialog.Builder(
            MyCaseActivity.this);

    alertDialog.setTitle("");
    alertDialog.setMessage("Are you sure you want to exit?");

    alertDialog.setPositiveButton("YES",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                    System.exit(0);
                }
            });

    alertDialog.setNegativeButton("NO",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

    alertDialog.show();
}

这对我有用。

于 2015-09-19T12:27:17.170 回答
2

尝试这个,

覆盖以下方法。

@Override
public boolean onKeyDown(int code, KeyEvent e) {
    Log.e(LOG_TAG, "down = " + code);
    if(code == KeyEvent.KEYCODE_BACK){
        return true;
    }else{
    return super.onKeyDown(code, e);
    }
}
于 2015-09-19T13:18:11.953 回答