Skip to content

Instantly share code, notes, and snippets.

@bolot
Last active August 15, 2017 14:24
Show Gist options
  • Save bolot/49880d593ba7db64339cff1c786cb02d to your computer and use it in GitHub Desktop.
Save bolot/49880d593ba7db64339cff1c786cb02d to your computer and use it in GitHub Desktop.
Kotlin SingleFragmentActivity
package com.bignerdranch.android.kotlin
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v7.app.AppCompatActivity
abstract class SingleFragmentActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_single_fragment)
addFragmentIfNeeded(R.id.container, this::createFragment)
}
abstract fun createFragment(): Fragment
}
fun FragmentActivity.addFragmentIfNeeded(container: Int, creator: () -> Fragment) {
supportFragmentManager.addFragmentIfNeeded(container, creator)
}
fun FragmentManager.addFragmentIfNeeded(container: Int, creator: () -> Fragment) {
findFragmentById(container) ?: beginTransaction().add(container, creator()).commit()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment