如何在按钮单击时清除片段堆栈和活动堆栈

时间:2015-07-31 02:07:21

标签: android android-fragments android-activity

有类似的问题,但没有一个是解决我的问题。 我的应用流程如下:

活动主页启动活动B(执行设置工作) 在活动B中,三个屏幕作为片段存在...... 片段1 - > fragment2->片段3.

这就是我制作片段的方式。我没有使用replace.just添加它。

FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        Fragment fragment = null;
        if (getFragType().equals("simple")) {
            fragment = new SimpleFragment().newInstance();
        }
        if (getFragType.equals("inter")) {
            if (getFragType.getComponent().equals("con"))
                fragment = new SetupConFragment().newInstance();
            else if (getFragType.getComponent().equals("ben"))
                fragment = new SetupBenageFragment().newInstance();
        }
        fragmentTransaction.add(R.id.fragment_container, fragment);
        fragmentTransaction.commit();
        }

Fragment3有一个完成按钮。因此,一旦从片段3开始完成所有3个步骤,就开始新的活动C.

问题是: - 从活动C开始,如果用户按下后退按钮,它会显示片段2,然后是片段1.理想情况下,一旦用户进入活动C,后退应该退出屏幕 我已经使用了intent标志的所有组合,但它没有帮助。

这是我的按钮点击。

Intent launch = new Intent(mContext, MainActivity.class);
                    launch.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    launch.putExtra("Exit me", true);
                    mContext.startActivity(launch);
                    ((ConfigureActivity)mContext).finish();

任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:5)

你可以这样做:

清除片段堆栈

getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); 

清除活动堆栈

Intent intent = new Intent(Your_Current_Activity.this, Your_Destination_Activity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK |Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

希望这会对你有所帮助。

答案 1 :(得分:2)

比如说,如果您想在活动A中启动活动B,但又不想让用户返回活动A,

final Intent intent = new Intent(this, ActivityB.class);
startActivity();
finish(); // kill the current activity (i.e., Activity A) so user cannot go back

答案 2 :(得分:0)

在您的活动C中,您可以通过覆盖onBackPressed()来控制返回键。

@Override
public void onBackPressed()
{
     // code here depending on your needs
}
相关问题