androidandroid-fragmentskotlinback-stackfragment-backstack

How can I remove my Activity setContentView from the Back Stack?


There are a hundred questions regarding this on Stackoverflow, but none of them are about my specific issue.

I'm starting my Activity with this code as a static function within my Activity class:

fun startForResult(activity: Activity, code: Int) {
    val intent = Intent(activity, MyActivity::class.java)
    activity.startActivityForResult(intent, code)
    activity.overridePendingTransition(R.anim.none, R.anim.none)
}

When MyActivity starts in runs onCreate and the setContentView(R.layout.activity) within it. This seems to go on the Back Stack. The Activity has only a FrameLayout which is full screen and is a placeholder/frame for the fragments I want to load. My Activity is very simple, like a wizard with 3 fragments/screens, all full screen. Once my activity OnCreate completes my presenter loads the first Fragment, FragmentA using code like this:

supportFragmentManager
    .beginTransaction()
    .replace(R.id.myContentFrame, FragmentA.newInstance())
    .addToBackStack(null)
    .commit()

This also goes on the back stack. The user presses the next button and my presenter runs this code:

supportFragmentManager
    .beginTransaction()
    .replace(R.id.myContentFrame, FragmentB.newInstance())
    .addToBackStack(null)
    .commit()

When the user presses the back button on FragmentB is takes the user back to FragmentA, which is fine. My problem occurs when they press the back button on FragmentA it takes them to a clear screen, which is apparently this setContentView(R.layout.activity) event, it's been added to the back stack and I'm going back to it. So I'd like to have that event, the start of the Activity, and its invisible layout NOT added to the back stack. When a user is on FragmentA and presses the back button I'd like the Activity to just finish. I've tried a bunch of different things to get rid of this setContentView(R.layout.activity) transaction in my back stack and nothing has worked. I assume there is an easy solution to this, like setting a FLAG, but it has eluded me. In the past I've overridden the OnBackPress method, and I assume that will work, but I'm still curious if there's an easier way to pop that first (Activity) item off my back stack without requiring me to override OnBackPressed.

What am I missing?


Solution

  • I think you no need add to back stack with fragment A. When in fragment A user back press Activity will be finish!