Fragment – “a small part broken or separated off something.”
Are they like mini activities? Are they super views? The Fragment has always been a source of controversy. Love or hate them, they are a fundamental component of the Android SDK, and when used correctly can really help supercharge your app!
Through concrete examples, you will learn best practices in regards to managing fragment transactions, staying on top of its lifecycle and tips on avoiding the most common pain points that developers face.
Finally, we’ll go through some advanced uses of fragments(headless fragments anyone?). And a quick example of how I used fragments to persist a web app in a hybrid application.
9. What is a Fragment?
“a small part broken or separated off something.”
Represent Portions of UIs in Activities
- Lifecycle
- Receive its own input events
- Added and removed using the Fragment manager
11. Dynamic Fragment
public class MainActivity extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
MatchlistFragment listFragment = new MatchlistFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container_list, listFragment)
.addToBackStack(null)
.commit();
15. Fragment Lifecycle
OnCreate -> initialize essential
components to be retained
OnCreateView -> First UI draw, return
UI here
onViewCreated -> initialise UI!
49. Solutions?
We can implement a backStackChangeListener()
We can override onBackPressed()
We can avoid the back stack modification, with child Fragments
57. Lesson #3
Be mindful of making fragment transactions/UI updates from async callbacks
58. Solutions?
Check if the fragment is Added to activity before updating UI
Add Flags in tear down lifecycle methods (onPause etc.)
Take out Async tasks!