Architecting Single-Activity Applications with or without Fragments
Presentation by Gabor Varadi (@zhuinden)
What Activity and Fragment actually are in Android
What are the problems they solve, and what are their downsides
How to use a custom solution that simplifies navigation in Android applications
„Starting an activity An Activity represents a single screen in an app. You can start a new instance of an Activity by passing an Intent to startActivity(). The Intent describes the activity to start and carries any necessary data.”
„A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities.”
Once we have gotten in to this entry-point to your UI, we really don't care how you organize the flow inside. Make it all one activity with manual changes to its views, use fragments (a convenience framework we provide) or some other framework, or split it into additional internal activities. Or do all three as needed. As long as you are following the high-level contract of activity (it launches in the proper state, and saves/restores in the current state), it doesn't matter to the system.
they are entry points to the app (like a main function) • The high-level Activity contract is showing UI for current state, handling initial state, and persist state across configuration change and process death • Fragments are just a „convenience framework” — technically they are ViewControllers with lifecycle integration • Android does NOT care how you handle the flow inside your application!
where you are in your application (and what to show) – where you came from, back/up navigation – remembering navigation state across config change and process death • Scoping – what data needs to be shown – what services need to exist (singleton and subscopes) – how to keep scoped services alive across config change
object can be exposed via the Context hierarchy by overriding getSystemService() • Objects from Activity (and the activity!) can be exposed directly via Activity.getSystemService() • Objects in subscope of Activity can be exposed through ContextWrapper.getSystemService() by inflating the view with a cloned layout inflater LayoutInflater.from(baseContext) .cloneInContext(contextWrapper);
duration of when the screen is visible, and not be killed on configuration changes. Child scopes should be able to inherit from their superscope. Things that set out to solve scoping problem: - Activity: onRetainCustomNonConfigurationInstance() - Fragment: retained fragments - Loaders - square/Mortar: MortarScope - lyft/Scoop: Scoop - zhuinden/Service-Tree: ServiceTree - Architectural Components: ViewModel
the data and services exist for as long as the scope • When the scope is destroyed (as it is no longer needed), the data and services are torn down along with it • In advanced use: – scoped data becomes a dependency that is provided to constructor, but obtained asynchronously and observed for changes (LiveData, BehaviorRelay, Observable + RxReplayingShare) – Dagger component is subscoped, and provides the data as scoped dependency – The Dagger component is stored in the scope to survive configuration changes
Singleton scope (and a single global injector), everything else is unscoped • Unscoped dependencies have their state persisted to Bundle, and restored if state exists • Also: if the ViewController is preserved even without its view hierarchy, then it can BE the scope! (retained fragments, Conductor’s Controller)
we have been • This state must be preserved across configuration changes and process death • Things that set out to solve Navigation problem: – Activity record stack – Fragment backstack – square/flow 0.8 – lyft/scoop – square/flow 1.0-alpha3 – terrakok/Cicerone (no backstack, only command queue) – bluelinelabs/Conductor – zhuinden/simple-stack – wealthfront/magellan (don’t use it – does NOT preserve state across process death!!!)
• Handling state persistence across config change / process death • Should receive both the previous and the new state on state change • Animations are asynchronous – operations must be enqueued • State changer is not always available (after onPause) – operations must be enqueued
Activities • Parameters are provided in the extras Bundle, generally as a dynamically typed storage with string keys • Intents have „intent flags” to manipulate „task stack” (CLEAR_TOP, REORDER_TO_FRONT, etc.) • Downsides: – You can’t easily tell what Activities exist in the background – Modifying stack needs tricky combinations of intent flags (no fine-grained control) – No notifications about change (previous state, new state) – Complicated lifecycle if multiple Activities exist
• Tutorials typically show „replace()” in conjunction with „addToBackStack()” • The backstack stores transactions (operations) with a tag to pop to (inclusive/exclusive) • (Parameters are also provided as Bundle, called arguments) • Downsides: – onBackstackChanged() provides change notification, but does not provide previous and new states (also it’s kinda random) – Stack stores operations instead of active fragments, so asymmetric navigation is super-difficult – commit() runs transaction on the NEXT event loop (what about onPause? „Cannot perform after onSaveInstanceState()”)
custom backstack to store current state and history • Content of the backstack is saved to and restored from Bundle (for process death) as Parcelables • State is represented as immutable parcelable value objects, called Keys • Keys contain all necessary data in order to set up the initial state (like Intent extras), but as typed values of the class • List of previous / new keys are both available („Traversal ”,…)
specifies what we want to show • We need to handle the events of the views (clicks, text changes, etc.) • For that, we need a „ViewController” (which can be used inside an Activity, so not an Activity) • Possible options: – Custom ViewGroup – Fragment – lyft/scoop’s ViewController – square/coordinators’s Coordinator – bluelinelabs/Conductor’s Controller
Activity provides them with lifecycle integration out of the box • FragmentManager keeps track of them and their state transitions • All added fragments are recreated after process death by super.onCreate() in Activity • (Supports nesting out of the box... with caveats)
– Add/remove: • Create fragment and its view hierarchy • Destroy view hierarchy, and fragment as well – Attach/detach: • Restore view state, (re-)create view hierarchy • preserve view state, but destroy view hierarchy – commitNow(): • Execute the fragment transaction synchronously • Note: this method cannot be used alongside addToBackStack() • Using these operators, we can combine this with a custom backstack, by keeping the fragments and their state alive, but only the currently visible view hierarchy.
were in previous state, but are no longer in the new state (if they are still in new state, then just detach them) • Create and add all fragments that are in the new state and not yet added • In the new state, if the current top already exists but is detached, then attach it, if it doesn’t exist, then create it and add it (and detach all other non-top fragments) • Commit transaction now