Fragments● “Part of the screen”● Introduced in Android 3.0 (API 11).● Available for older Android platforms via support package / library.● Allows us to change activity appearance at runtime without complex changes.
Creating a fragment● Extend Fragment class.● Implement fragment Callbacks.
Fragment life cycle
Fragment Callbacks● OnCreate() – Called when first creating the fragment. – Initialize members here.● OnCreateView() – Called when the fragments needs to be displayed on screen. – Must return a view object.
Fragment Callbacks● OnPause() – Called when the user leaves the fragment● OnDestroy – Called when fragment is destroyed.
Adding fragment to activity / layout
Adding fragment to activity● Activity should extends fragmentActivity instead of Activity
Communicating with the activity● Fragment side: – GetActivity() - returns a reference to the containing activity.● Activity Side:
Communicating with activity● Often a fragment needs to share events with its activity. – For example: itemClicked.● Fragment should define a callback interface
Communicating with activity - cont● Activity should implement that callback interface.● Fragment holds reference to that listener and notifies it when needed.
Checkpoint 0● Checkout checkpoint0 branch from https://github.com/RanNachmany/AndconLab● Adjust project to use actionBarSherlock● Run.
Checkpoint 1● Create a fragment that displays a list of all lectures.● Change MainActivity to use the new fragment.● Do the same for SingleLectureActivity.● Dont forget to implement callback interface.
Supporting tablets● How activity A will change its layout from one fragment to two dynamically?● The answer: xml qualifiers. – We will create two xml layouts. One for phone, and one for tablet. – OS will choose the right layout during runtime. – Good qualifier: sw-600. Smallest width: 600. ● Located at res/layout-sw600dp
Changing fragments programatically
Checkpoint 2● Add main_activity layout under sw-600 qualifier.● Adjust MainActivity code.● Test on phone and tablet.● Bring world peace.