Hi I have activity A that contains fragment x. the...
# android
m
Hi I have activity A that contains fragment x. then I open fragment y from it. then I open Activity B from fragment y. When i press back from Activity B, it opens fragment y. Is there anyway to open fragment x when i press back from Activity B? i thought that not setting
addToBackstack()
would help me but it is only responsible for previous fragment not the new one.
r
Not Kotlin related
j
This is only Android related, but if you're using Navigation Components you're probably looking for
popupTo
/
popupToInclusive
. https://developer.android.com/guide/navigation/navigation-navigate
m
Yeah i know about navigation component and i wanna change project to use it. But it is not right time in my company to do this. So i should find another way for this
i
Fragments always remember the exact state you leave them in across configuration changes, process death and recreation, and going to another activity and coming back. Therefore if you want to remove Fragment y and only have Fragment x, you need to do that FragmentTransaction yourself (probably right before you call startActivity on Activity B, so that Activity A is already in the right state when you return to it)
👍 2
m
Hi Ian. Thanks for answering my question again. I know the best way is to use
Navigation Component
but because of force of our project, I can not do that in this time. I just do that in a weird way. I started activity B from fragment y by calling
startActivityForResult()
and then when i press back in activity B, I call
setResult(RESULT_OK)
Then in fragment y i do this:
Copy code
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == REQUEST_CODE){
        parentFragmentManager.popBackStack (this::class.java.name,
            FragmentManager.POP_BACK_STACK_INCLUSIVE)
    }
}
Actually, I use class names as their name in backstack. I know this is not good way, but at least it works for me :)
i
Sure, that would be a fine approach if you wanted to conditionally pop the back stack (i.e., only when it is
RESULT_OK
), but you don't seem to have any condition like that so putting your Activity A in the right state ahead of time is going to 1) remove the need to save and restore Fragment y at all 2) set you up for animations, transitions (which would not be easy if you do this just in time approach)