Skip to content

Instantly share code, notes, and snippets.

@osipxd
Last active January 16, 2020 13:11
Show Gist options
  • Save osipxd/dd97b1d7e06d99a4f9894469e1fa0d60 to your computer and use it in GitHub Desktop.
Save osipxd/dd97b1d7e06d99a4f9894469e1fa0d60 to your computer and use it in GitHub Desktop.
Activity wrapper for any fragment
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
package com.example
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import com.example.R
import com.example.BaseActivity
class FragmentContainerActivity : BaseActivity() {
companion object {
inline fun fromFactory(
context: Context,
crossinline createFragment: () -> Fragment
): Intent {
return Intent(context, FragmentContainerActivity::class.java).apply {
putFragmentFactory(createFragment)
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_fragment_container)
if (savedInstanceState == null) {
val fragmentFactory = intent.getFragmentFactory()
this.changeFragment(fragmentFactory.createFragment())
.commit()
}
}
}
package com.example
import android.content.Context
import android.content.Intent
import androidx.annotation.StringRes
import androidx.fragment.app.Fragment
import java.io.Serializable
const val FRAGMENT_FACTORY = "fragment_factory"
interface FragmentFactory : Serializable {
fun createFragment(): Fragment
}
inline fun Intent.putFragmentFactory(crossinline createFragment: () -> Fragment) {
val factory = object : FragmentFactory {
override fun createFragment(): Fragment = createFragment()
}
putExtra(FRAGMENT_FACTORY, factory)
}
fun Intent.getFragmentFactory(): FragmentFactory {
return getSerializableExtra(FRAGMENT_FACTORY) as FragmentFactory
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment