Created
July 23, 2016 18:21
-
-
Save AaronC81/8c05a978f4cc514bcb0ddf651e1c8ab5 to your computer and use it in GitHub Desktop.
Anko Fragments v3
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
import android.app.Activity | |
import android.app.Fragment | |
import android.content.Context | |
import android.view.View | |
import android.view.ViewManager | |
import android.widget.RelativeLayout | |
import org.jetbrains.anko.custom.ankoView | |
/** | |
* @property childFragment The Fragment which this view should contain. Setting this value will destroy previous fragments and commit the new one. | |
* @constructor Creates a new FragmentView. | |
*/ | |
class FragmentView(ctx: Context) : RelativeLayout(ctx) { | |
var childFragment: Fragment? = null | |
get() = field | |
set(value) { | |
// Destroy the existing fragment if there is one | |
if (childFragment != null) (context as Activity).fragmentManager.beginTransaction().remove(childFragment).commit() | |
// Create and commit the new fragment | |
field = value | |
if (field == null) { return } | |
(context as Activity).fragmentManager.beginTransaction().add(id, field).commit() | |
} | |
init { | |
// Get an ID | |
this.id = View.generateViewId() | |
} | |
} | |
// Anko support | |
inline fun ViewManager.fragmentView(theme: Int = 0) = fragmentView(theme) {} | |
inline fun ViewManager.fragmentView(theme: Int = 0, init: FragmentView.() -> Unit) = ankoView({ FragmentView(it) }, theme, init) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment