Last active
August 15, 2017 14:24
-
-
Save bolot/49880d593ba7db64339cff1c786cb02d to your computer and use it in GitHub Desktop.
Kotlin SingleFragmentActivity
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.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