smash your android app into fragments
TRANSCRIPT
1. Whats the Problem? 2. What Are Fragments? 3. How Do I Use Fragments 4. Look at Code! 5. What about Backwards
Compatibility?
Things We’ll Talk About
❖ User Interface “modules” ❖ Can share Fragments across different
activity ❖ On Activity can have many
fragments ❖ Different screen sizes have different
layouts
What are Fragments?
❖ Android 3.0 or Higher (well, sort of/not really) ❖ Subclass the Fragment base class ❖ They can load Layout files / Create it’s UI similar to an Activity ❖ There are specialized fragments ❖ Fragments have a lifecycle, just like Activities
Fragment Basics
Fragment Lifecycle
Start
OnInflate OnAttach
OnCreate
OnCreateView
OnActivityCreated
OnStart
OnResumeOnPause
OnStop
OnDestroyView
OnDestroy
OnDetachRunning
End
Fragment Lifecycle (Realistically)
Start
OnInflate OnAttach
OnCreate
OnCreateView
OnActivity
CreatedOnStart
OnResumeOnPause
OnStop
OnDestroyView
OnDestroy
OnDetachRunning
End
Fragments Need Help❖ Must be hosted in an Activity ❖ Activities are Not Directly Aware of
their Fragments ❖ Fragments are aware of their host
Activity ❖ Fragments are not aware of other
Fragments ❖ FragmentManager is the middle man
Fragment Manager
Activity
FragmentManager
FragmentFragmentFragmentFragment Find Fragment
1. Activity looking for a Fragment
2. Searches Fragments
3. Found the request Fragment
Adding a Static Fragment<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent"> <fragment class="net.opgenorth.shakespeare.TitlesFragment" android:id="@+id/titles_fragment" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout>
Adding a Dynamic Fragment
// Make new fragment to show this selection. DetailsFragment details = new DetailsFragment();
// Execute a transaction, adding the fragment to the FrameLayout. FragmentTransaction ft = FragmentManager.beginTransaction(); ft.add(Resource.Id.details, details, "details_fragment"); ft.commit();
Android Support Libraries❖ A set of code libraries that provide
backwards compatibility and features to older API levels
❖ Building a Dynamic UI with Fragments - http://developer.android.com/training/basics/fragments/index.html
❖ Support Libraries - http://developer.android.com/tools/support-library/index.html
Links / References