问题描述
我可以操作栏中的向上导航触发确认dialogfragment,说:你确定你想回去吗?
Can I make the action bar's "up" navigation trigger a confirmation dialogfragment that says "Are you sure you would like to go back?"
推荐答案
截获最高
动作条按钮preSS是微不足道的,因为一切都是通过<$ C $完成C> onOptionsItemSelected 。该文档,建议您使用机器人。 R.id.home
去了 NavUtils
(前提是你设置的元数据父活动让 NavUtils
不抛出异常等):
Intercepting the up
ActionBar button press is trivial because everything is done through onOptionsItemSelected
. The documentation, recommends that you use android.R.id.home
to go up with NavUtils
(provided that you set the metadata for the parent activity so NavUtils
doesn't throw an Exception, etc):
@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
应该提供一个确认实际回去。既然你现在正与片段
,而不是活动
,你会想通过 getActivity()
到 NavUtils
。
Your DialogFragment
should offer an confirmation to actually go back. Since you're now working with the Fragment
and not the Activity
, you're going to want to pass getActivity()
to 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
。
注意,在这个例子中,我使用了支持
片段
的API ,.如果你不是,请确保更改 getSupportFragmentManager()
到 getFragmentManager()
。
Note that for this example, I am using the support
Fragment
APIs,. If you are not, make sure to change getSupportFragmentManager()
to getFragmentManager()
.
这篇关于请行动起来吧&QUOT;向上导航&QUOT;触发dialogfragment的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!