Created
November 25, 2019 02:50
-
-
Save androuino/2242587497843ce1084e1ea61e9dc4be to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.mvvm.ui | |
import androidx.fragment.app.FragmentManager | |
import androidx.fragment.app.FragmentTransaction | |
import com.example.mvvm.R | |
import com.example.mvvm.ui.base.BaseFragment | |
import com.example.mvvm.ui.base.BaseKey | |
import com.example.mvvm.ui.main.MainActivity | |
import com.zhuinden.simplestack.StateChange | |
/** | |
* Created by Owner on 2017. 06. 29.. | |
*/ | |
class FragmentStateChanger( | |
private val activity: MainActivity, | |
private val fragmentManager: FragmentManager, | |
private val containerId: Int | |
) { | |
fun handleStateChange(stateChange: StateChange) { | |
val fragmentTransaction: FragmentTransaction = fragmentManager.beginTransaction().disallowAddToBackStack() | |
if (stateChange.direction == StateChange.FORWARD) { | |
fragmentTransaction.setCustomAnimations( | |
R.anim.slide_in_from_right, | |
R.anim.slide_out_to_left, | |
R.anim.slide_in_from_right, | |
R.anim.slide_out_to_left | |
) | |
} else if (stateChange.direction == StateChange.BACKWARD) { | |
fragmentTransaction.setCustomAnimations( | |
R.anim.slide_in_from_left, | |
R.anim.slide_out_to_right, | |
R.anim.slide_in_from_left, | |
R.anim.slide_out_to_right | |
) | |
} | |
val previousState: List<BaseKey<*>> = stateChange.getPreviousKeys<BaseKey<*>>() | |
val newState: List<BaseKey<*>> = stateChange.getNewKeys<BaseKey<*>>() | |
for (oldKey in previousState) { | |
val fragment = fragmentManager.findFragmentByTag(oldKey.fragmentTag) | |
if (fragment != null) { | |
if (!newState.contains(oldKey)) { | |
fragmentTransaction.remove(fragment) | |
} else if (!fragment.isDetached) { | |
fragmentTransaction.detach(fragment) | |
} | |
} | |
} | |
for (newKey in newState) { | |
var fragment: BaseFragment<*> = fragmentManager.findFragmentByTag(newKey.fragmentTag) as BaseFragment<*> | |
if (newKey == stateChange.topNewKey()) { | |
if (fragment.isRemoving) { // Fragments are quirky, they die asynchronously. Ignore if they're still there. | |
fragment = newKey.newFragment() | |
fragmentTransaction.replace(containerId, fragment, newKey.fragmentTag) | |
} else if (fragment.isDetached) { | |
fragmentTransaction.attach(fragment) | |
} | |
} else { | |
if (!fragment.isDetached) { | |
fragmentTransaction.detach(fragment) | |
} | |
} | |
// bindViewModel here being captioned as Unreachable code | |
fragment.bindViewModel(activity.backstackDelegate.getService(newKey, newKey.viewModelTag)) | |
} | |
fragmentTransaction.commitNow() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment