Skip to content

Instantly share code, notes, and snippets.

@comm1x
Created December 2, 2019 10:58
Show Gist options
  • Save comm1x/41d7e7b1c9d45c23b19011e6f8e52df1 to your computer and use it in GitHub Desktop.
Save comm1x/41d7e7b1c9d45c23b19011e6f8e52df1 to your computer and use it in GitHub Desktop.
Single Activity implementation
class AppActivity: AppCompatActivity() {
companion object {
fun newInstance(context: Context) = Intent(context, AppActivity::class.java)
}
internal val navigationFragment = NavigationFragment()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val rootFrameLayout = FrameLayout(this).apply {
id = View.generateViewId()
layoutParams = LayoutParams(MATCH_PARENT, MATCH_PARENT)
}
setContentView(rootFrameLayout)
supportFragmentManager.beginTransaction()
.replace(rootFrameLayout.id, navigationFragment)
.commit()
}
override fun onBackPressed() {
if (navigationFragment.childFragmentManager.fragments.isNotEmpty()) {
navigationFragment.childFragmentManager.popBackStack()
} else {
super.onBackPressed()
}
}
}
class NavigationFragment: Fragment() {
internal lateinit var root: View
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
root = FrameLayout(context).apply {
id = View.generateViewId()
layoutParams = LayoutParams(MATCH_PARENT, MATCH_PARENT)
}
return root
}
internal fun setRootFragment(fragment: Fragment) {
childFragmentManager.beginTransaction().replace(root.id, fragment).commit()
}
fun pushFragment(fragment: Fragment) {
childFragmentManager.beginTransaction()
.replace(root.id, fragment)
.addToBackStack(null)
.commit()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment