Skip to content

Instantly share code, notes, and snippets.

@marcellogalhardo
Created June 1, 2021 16:05
Show Gist options
  • Save marcellogalhardo/dc6bdfbb6fa6c8c696d238a8be61935e to your computer and use it in GitHub Desktop.
Save marcellogalhardo/dc6bdfbb6fa6c8c696d238a8be61935e to your computer and use it in GitHub Desktop.
A default AppCompatActivity that hosts a Fragment.
<?xml version="1.0" encoding="utf-8"?>
<androidx.fragment.app.FragmentContainerView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragmentContainerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
import android.content.Intent
import android.os.Bundle
import androidx.annotation.CallSuper
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentContainerView
import androidx.fragment.app.commitNow
import com.deliveryhero.commons.mvvm.R
import kotlin.reflect.KClass
/**
* A default [AppCompatActivity] that hosts a [Fragment].
*
* [SingleFragmentActivity] has a default layout [R.layout.activity_single_fragment]
* that consists of a single, full-screen [FragmentContainerView] in the center of the
* screen.
*
* Any extra set in the activity [Intent] will be automatically redirect to the
* displayed [Fragment].
*
* [SingleFragmentActivity] was designed to be used when migrating to a "Single
* Activity Architecture" in small steps: first converting multiple activities to
* fragments hosted by multiple [SingleFragmentActivity] without breaking changes
* and finally, using a NavGraph - if you are planning to use JetPack Navigation -
* to do the wiring of all these fragments inside a host [AppCompatActivity].
*
* Note this class has been designed to support child fragments, but you should
* NOT change the single fragment or this would result in unexpected behaviour.
*
* Usage example:
* ```
* class MyActivity : SingleFragmentActivity(MyFragment::class)
* ```
*/
abstract class SingleFragmentActivity(
private val fragmentClass: KClass<out Fragment>
) : AppCompatActivity() {
@CallSuper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_single_fragment)
supportFragmentManager.findFragmentById(R.id.fragmentContainerView) ?: return
val fragment = supportFragmentManager.fragmentFactory
.instantiate(classLoader, fragmentClass.java.name)
.apply { arguments = intent?.extras }
supportFragmentManager.commitNow {
setReorderingAllowed(true)
add(R.id.fragmentContainerView, fragment)
setPrimaryNavigationFragment(fragment)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment