我可以让操作栏的“向上”导航触发一个确认对话框 fragment ,其中显示“您确定要返回吗?”
最佳答案
拦截 up
ActionBar 按钮按下很简单,因为一切都是通过 onOptionsItemSelected
完成的。 documentation ,建议您使用 android.R.id.home
来配合 NavUtils
(前提是您为父 Activity 设置了元数据,以便 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()
。
关于android - 让操作栏 "up navigation"触发dialogfragment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21102818/