我可以使操作栏的“向上”导航触发一个确认对话框片段,该片段显示“您确定要返回吗?”

最佳答案

拦截up按下ActionBar按钮很简单,因为所有事情都是通过onOptionsItemSelected完成的。 documentation,建议您使用android.R.id.homeNavUtils保持一致(前提是您为父活动设置了元数据,以便NavUtils不会引发异常,等等):

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    // Respond to the action bar's Up/Home button
    case android.R.id.home:
        NavUtils.navigateUpFromSameTask(this);
        return true;
    }
    return super.onOptionsItemSelected(item);
}


您的DialogFragment应该提供确认以实际返回。由于您现在使用的是Fragment而不是Activity,因此您需要将getActivity()传递给NavUtils

NavUtils.navigateUpFromSameTask(getActivity());


并将onOptionsItemSelected()更改为

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    // Respond to the action bar's Up/Home button
    case android.R.id.home:
        new ConfirmationDialog().show(getSupportFragmentManager(), "confirmation_dialog");
        return true;
    }
    return super.onOptionsItemSelected(item);
}


ConfirmationDialog是您的自定义DialogFragment

请注意,对于本示例,我使用的是support Fragment API。如果不是,请确保将getSupportFragmentManager()更改为getFragmentManager()

07-28 12:23