我可以使操作栏的“向上”导航触发一个确认对话框片段,该片段显示“您确定要返回吗?”
最佳答案
拦截up
按下ActionBar按钮很简单,因为所有事情都是通过onOptionsItemSelected
完成的。 documentation,建议您使用android.R.id.home
与NavUtils
保持一致(前提是您为父活动设置了元数据,以便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()
。