在活动中使用 OnBackPressed 方法的一个片段到另一个片段
Posted
技术标签:
【中文标题】在活动中使用 OnBackPressed 方法的一个片段到另一个片段【英文标题】:One fragment To Another fragment using OnBackPressed method in activity 【发布时间】:2021-11-23 01:52:10 【问题描述】:我的问题很简单,当我按下返回按钮时,它将转到上一个片段,我该怎么做?当我在对话中单击“是”按钮时,如果我单击没有进入前一个片段的按钮,它将完成显示..
@Override
public void onBackPressed()
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setMessage("Do you want to Exit?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener()
@Override
public void onClick(DialogInterface dialog, int which)
//if user pressed "yes", then he is allowed to exit from application
finish();
);
builder.setNegativeButton("No",new DialogInterface.OnClickListener()
@Override
public void onClick(DialogInterface dialog, int which)
//if user select "No", just cancel this dialog and continue with app
dialog.cancel();
);
AlertDialog alert=builder.create();
alert.show();
【问题讨论】:
【参考方案1】:首先如果你提交任何片段添加 addToBackStack()
getSupportFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.nav_host_fragment,new NewFragment()).commit();
然后
@Override
public void onBackPressed()
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
getSupportFragmentManager().popBackStack();
else
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setMessage("Do you want to Exit?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener()
@Override
public void onClick(DialogInterface dialog, int which)
//if user pressed "yes", then he is allowed to exit from application
finish();
);
builder.setNegativeButton("No",new DialogInterface.OnClickListener()
@Override
public void onClick(DialogInterface dialog, int which)
//if user select "No", just cancel this dialog and continue with app
dialog.cancel();
);
AlertDialog alert=builder.create();
alert.show();
【讨论】:
以上是关于在活动中使用 OnBackPressed 方法的一个片段到另一个片段的主要内容,如果未能解决你的问题,请参考以下文章
在单个活动 android 应用程序中管理 onBackPressed
从 dialogfragment 调用 onBackPressed 完成活动
onBackPressed 上的 Android 片段 NullPointerException