際際滷

際際滷Share a Scribd company logo
Smashing your Android
App Into Fragments
Tom Opgenorth |
tom@opgenorth.net
A Word From Our Sponsors
1. Whats the Problem?
2. What Are Fragments?
3. How Do I Use Fragments
4. Look at Code!
5. What about Backwards
Compatibility?
Things Well Talk About
What Involved
Whats the Problem?
Smash your Android App into Fragments
Screen Sizes & Densities
Smash your Android App into Fragments
Fragments To The Rescue!
What is Fragment?
A Fragment represents a
behaviour or portion of user
interface in an Activity.
 User Interface modules
 Can share Fragments across different
activity
 On Activity can have many
fragments
 Different screen sizes have different
layouts
What are Fragments?
Smash your Android App into Fragments
 Android 3.0 or Higher (well, sort of/not really)
 Subclass the Fragment base class
 They can load Layout files / Create its UI similar to an Activity
 There are specialized fragments
 Fragments have a lifecycle, just like Activities
Fragment Basics
Fragment Lifecycle
Start
OnIn鍖ate
OnAttach
OnCreate
OnCreate
View
OnActivity
Created
OnStart
OnResume
OnPause
OnStop
OnDestroy
View
OnDestroy
OnDetachRunning
End
Fragment Lifecycle (Realistically)
Start
OnIn鍖ate
OnAttach
OnCreate
OnCreate
View
OnActivit
y
Created
OnStart
OnResume
OnPause
OnStop
OnDestroy
View
OnDestroy
OnDetachRunning
End
How Do I Create
Fragments?
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
Fragment
Manager
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();
Show Me The Code!
Backwards Compatibility
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
Thank You!
Questions?

More Related Content

Smash your Android App into Fragments