SlideShare ist ein Scribd-Unternehmen logo
1 von 37
Android application development 
Android Fragments
Fragment 
• An activity is a container for views 
• When you have a larger screen device than a phone –like a 
tablet it can look too simple to use phone interface here. 
•  Fragments 
• Mini-activities, each with its own set of views 
• One or more fragments can be embedded in an Activity 
• You can do this dynamically as a function of the device type (tablet or not) 
or orientation
Fragment Idea 
•  Fragments 
• Mini-activities, each with its own set of views 
• One or more fragments can be embedded in an Activity 
• You can do this dynamically as a function of the device type (tablet or not) 
or orientation 
You might 
decide to run 
a tablet in 
portrait mode 
with the handset 
model of only 
one fragment 
in an Activity
Fragment 
• 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. 
• You can think of a fragment as a modular section 
of an activity, which has its own lifecycle, receives 
its own input events, and which you can add or 
remove while the activity is running (sort of like a 
"sub activity" that you can reuse in different 
activities).
Fragment Lifecycle 
• Fragment in an Activity---Activity 
Lifecyle influences 
– Activity paused  all its fragments paused 
– Activity destroyed  all its fragments paused 
– Activity running  manipulate each fragment 
independently. 
• Fragment transaction add, 
remove, etc. 
– adds it to a back stack that's managed by the activity— 
each back stack entry in the activity is a record of the 
fragment transaction that occurred. 
– The back stack allows the user to reverse a fragment 
transaction (navigate backwards), by pressing the Back 
button.
Fragment inside Activity 
• it lives in a ViewGroup inside the activity's view 
hierarchy 
• fragment has its own view layout. 
• via XML: Insert a fragment into your activity 
layout by declaring the fragment in the activity's 
layout file, as a <fragment> element, 
• via CODE: from your application code by adding 
it to an existing ViewGroup. 
• you may also use a fragment without its own UI 
as an invisible worker for the activity.
Fragment – extend a Fragment class 
• via CODE: extend android.app.Fragment OR 
one of its subclasses (DialogFragment, 
ListFragment, PreferenceFragment, 
WebViewFragment ) 
• IMPORTANT: must include a public empty constructor. The 
framework will often re-instantiate a fragment class when needed, in 
particular during state restore, and needs to be able to find this 
constructor to instantiate it. If the empty constructor is not available, a 
runtime exception will occur in some cases during state restore. 
• CALL Back functions (like Activity) : examples onCreate(), onStart(), 
onPause(), and onStop().
Fragment methods (callback functions) 
• onAttach(Activity) called once the fragment is associated with its 
activity. 
• onCreate(Bundle) called to do initial creation of the fragment. 
• onCreateView(LayoutInflater, ViewGroup, Bundle) creates and 
returns the view hierarchy associated with the fragment. 
• onActivityCreated(Bundle) tells the fragment that its activity has 
completed its own Activity.onCreaate. 
• onStart() makes the fragment visible to the user (based on its 
containing activity being started). 
• onResume() makes the fragment interacting with the user (based 
on its containing activity being resumed).
Fragment methods (callback functions) 
As a fragment is no longer being used, it goes through a reverse series of 
callbacks: 
• onPause() fragment is no longer interacting with the user either because 
its activity is being paused or a fragment operation is modifying it in the 
activity. 
• onStop() fragment is no longer visible to the user either because its 
activity is being stopped or a fragment operation is modifying it in the 
activity. 
• onDestroyView() allows the fragment to clean up resources associated 
with its View. 
• onDestroy() called to do final cleanup of the fragment's state. 
• onDetach() called immediately prior to the fragment no longer being 
associated with its activity.
Create your own Fragment class or use 
known sub-classes 
• DialogFragment Displays a floating dialog. Using this class to create a 
dialog is a good alternative to using the dialog helper methods in the 
Activity class, because you can incorporate a fragment dialog into the back 
stack of fragments managed by the activity, allowing the user to return to 
a dismissed fragment. 
• ListFragment Displays a list of items that are managed by an adapter (such 
as a SimpleCursorAdapter), similar to ListActivity. It provides several 
methods for managing a list view, such as the onListItemClick() callback to 
handle click events. 
• PreferenceFragment Displays a hierarchy of Preference objects as a list, 
similar to PreferenceActivity. This is useful when creating a "settings" 
activity for your application.
Fragments and their UI 
• Most fragments will have a UI 
• Will have its own layout 
• you must implement the onCreateView() 
callback method, which the Android system 
calls when it's time for the fragment to draw 
its layout. Your implementation of this method 
must return a View that is the root of your 
fragment's layout.
Fragments and their UI – 
onCreateView() using XML 
• Can implement onCreateView using XML 
public static class ExampleFragment extends Fragment { 
@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
Bundle savedInstanceState) { 
// Inflate the layout for this fragment 
return inflater.inflate(R.layout.example_fragment, container, false); 
} 
} 
Bundle that provides data about the previous 
instance of the fragment, if the fragment is being resumed 
Have example_fragment.xml file that contains the layout 
This will be contained in resource layout folder. 
Activity parent’s 
ViewGroup
OPTION1 –adding to an Activity via 
Activity layout XML. 
<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="horizontal" 
android:layout_width="match_parent" 
android:layout_height="match_parent"> 
<fragment android:name="com.example.news.ArticleListFragment" 
android:id="@+id/list" 
android:layout_weight="1" 
android:layout_width="0dp" 
android:layout_height="match_parent" /> 
<fragment android:name="com.example.news.ArticleReaderFragment" 
android:id="@+id/viewer" 
android:layout_weight="2" 
android:layout_width="0dp" 
android:layout_height="match_parent" /> 
</LinearLayout> 
2 fragment classes 
Need unique ids for each so system can 
restore the fragment if the activity is restarted
OPTION2 –creating and adding to an 
Activity via CODE. 
/*Inside Activity Code where you want to add Fragment (dynamically anywhere or in onCreate() 
callback) 
*/ 
//get FragmentTransaction associated with this Activity 
FragmentManager fragmentManager = getFragmentManager(); 
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 
//Create instance of your Fragment 
ExampleFragment fragment = new ExampleFragment(); 
This points to the Activity ViewGroup in 
which the fragment should be placed, 
specified by resource ID 
//Add Fragment instance to your Activity 
fragmentTransaction.add(R.id.fragment_container, fragment); 
fragmentTransaction.commit();
OPTION 3- Adding Fragment that has 
NO UI using Code 
• use a fragment to provide a background behavior for the activity without 
presenting additional UI. 
• use add(Fragment, String) (supplying a unique string "tag" for the 
fragment, rather than a view ID). 
– it's not associated with a view in the activity layout, it does not receive a call to 
onCreateView(). So you don't need to implement that method. 
• If you want to get the fragment from the activity later, you need to use 
findFragmentByTag(). 
• For an example activity that uses a fragment as a background worker, 
without a UI, see the FragmentRetainInstance.java sample. 
• STOP AND LOOK AT EXAMPLE ON OUR OUTLINE!!!!!!
Managing Fragments 
FragmentManager methods: 
• Get fragments that exist in Activity = 
– findFragmentById() (for fragments that provide a UI in the activity layout) 
– findFragmentByTag() (for fragments that do or don't provide a UI). 
• Pop fragments off the back stack, 
– popBackStack() (simulating a Back command by the user). 
• Register a listener for changes to the back stack, 
– addOnBackStackChangedListener().
Fragment Transactions – adding, removing and 
replacing dynamically 
// Create new fragment and transaction 
Fragment newFragment = new ExampleFragment(); 
FragmentTransaction transaction getFragmentManager().beginTransaction(); 
// Replace whatever is in the fragment_container view with this fragment 
// and add the transaction to the back stack 
transaction.replace(R.id.fragment_container, newFragment); 
transaction.addToBackStack(null); 
// Commit the transaction 
transaction.commit(); 
newFragment replaces whatever fragment 
(if any) is currently in the layout container 
identified by the R.id.fragment_container 
If you do not call addToBackStack() when you perform a transaction 
that removes a fragment, then that fragment is destroyed when the 
transaction is committed and the user cannot navigate back to it. 
Whereas, if you do call addToBackStack() when removing a 
fragment, 
then the fragment is stopped and will be resumed if the user 
navigates back.
Let’s Make a Fragment Project
Lets Create a new project 
Fragment Basics 
Which Main Activity extends Fragment Activity
Our Project 
Structure
Create news_articles.xml
Create article_view.xml
Create layout-large/news_articles.xml
HeadlinesFragment.java 
 The container Activity must implement this interface 
“OnHeadlineSelectedListener mCallback;” so the 
fragment can deliver messages
onStart() & onAttach(Activity activity)
onListItemClick() 
 Notify the parent activity of selected item 
 Set the item as checked to be highlighted when in two-pane layout
ArticalFragment.java 
 If activity recreated (such as from screen rotate), restore the 
previous article selection set by onSaveInstanceState(). 
 Inflate the layout for this fragment
Article Fragment OnStart() 
 During startup, check if there are arguments passed to the 
fragment. 
 Set article based on argument passed in
Update ArticleView(int position) 
• Set Article on TextView
Now Back in MainActivity 
In onCreate() 
• Check whether the activity is using the layout version with 
the fragment_container FrameLayout. 
If so, we must add the first fragment 
• Create an instance of HeadlinesFragment 
• In case this activity was started with special instructions 
from an Intent, pass the Intent's extras to the fragment as 
arguments 
• Add the fragment to the 'fragment_container' FrameLayout
In onArticleSelected(int position) 
• Capture the article fragment from the activity layout 
• If article fragment is available, we're in two-pane layout then 
Call a method in the ArticleFragment to update its content 
• If the fragment is not available, we're in the one-pane layout and must 
swap fragments Create fragment and give it an argument for the selected 
article 
• Replace whatever is in the fragment_container view with this fragment, 
and add the transaction to the back stack so the user can navigate back 
• Commit the transaction
Check Manifest XML
Output at TAB
Output In Phone
Thank You

Weitere ähnliche Inhalte

Was ist angesagt?

04 activities and activity life cycle
04 activities and activity life cycle04 activities and activity life cycle
04 activities and activity life cycleSokngim Sa
 
RichControl in Asp.net
RichControl in Asp.netRichControl in Asp.net
RichControl in Asp.netBhumivaghasiya
 
Layouts in android
Layouts in androidLayouts in android
Layouts in androidDurai S
 
[Android] Widget Event Handling
[Android] Widget Event Handling[Android] Widget Event Handling
[Android] Widget Event HandlingNikmesoft Ltd
 
Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in javaAdil Mehmoood
 
Android Telephony Manager and SMS
Android Telephony Manager and SMSAndroid Telephony Manager and SMS
Android Telephony Manager and SMSJussi Pohjolainen
 
Fragments In Android
Fragments In AndroidFragments In Android
Fragments In AndroidDivyaKS12
 
Android share preferences
Android share preferencesAndroid share preferences
Android share preferencesAjay Panchal
 
Events and Listeners in Android
Events and Listeners in AndroidEvents and Listeners in Android
Events and Listeners in Androidma-polimi
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events WebStackAcademy
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in javaGoogle
 
Android notification
Android notificationAndroid notification
Android notificationKrazy Koder
 
Menu bars and menus
Menu bars and menusMenu bars and menus
Menu bars and menusmyrajendra
 
Android User Interface Tutorial: DatePicker, TimePicker & Spinner
Android User Interface Tutorial: DatePicker, TimePicker & SpinnerAndroid User Interface Tutorial: DatePicker, TimePicker & Spinner
Android User Interface Tutorial: DatePicker, TimePicker & SpinnerAhsanul Karim
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivityTanmoy Barman
 

Was ist angesagt? (20)

Android Fragment
Android FragmentAndroid Fragment
Android Fragment
 
04 activities and activity life cycle
04 activities and activity life cycle04 activities and activity life cycle
04 activities and activity life cycle
 
RichControl in Asp.net
RichControl in Asp.netRichControl in Asp.net
RichControl in Asp.net
 
Layouts in android
Layouts in androidLayouts in android
Layouts in android
 
Action Bar in Android
Action Bar in AndroidAction Bar in Android
Action Bar in Android
 
[Android] Widget Event Handling
[Android] Widget Event Handling[Android] Widget Event Handling
[Android] Widget Event Handling
 
Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in java
 
Android Telephony Manager and SMS
Android Telephony Manager and SMSAndroid Telephony Manager and SMS
Android Telephony Manager and SMS
 
Fragments In Android
Fragments In AndroidFragments In Android
Fragments In Android
 
Android share preferences
Android share preferencesAndroid share preferences
Android share preferences
 
Events and Listeners in Android
Events and Listeners in AndroidEvents and Listeners in Android
Events and Listeners in Android
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
Asp.net.
Asp.net.Asp.net.
Asp.net.
 
Android notification
Android notificationAndroid notification
Android notification
 
05 intent
05 intent05 intent
05 intent
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Menu bars and menus
Menu bars and menusMenu bars and menus
Menu bars and menus
 
Android User Interface Tutorial: DatePicker, TimePicker & Spinner
Android User Interface Tutorial: DatePicker, TimePicker & SpinnerAndroid User Interface Tutorial: DatePicker, TimePicker & Spinner
Android User Interface Tutorial: DatePicker, TimePicker & Spinner
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 

Andere mochten auch

Android - Working with Fragments
Android - Working with FragmentsAndroid - Working with Fragments
Android - Working with FragmentsCan Elmas
 
Mobile Application capacity building activities
Mobile Application capacity building activities Mobile Application capacity building activities
Mobile Application capacity building activities nationalmobileapps
 
Introduction to Android Fragments
Introduction to Android FragmentsIntroduction to Android Fragments
Introduction to Android FragmentsSergi Martínez
 
Android App Development - 06 Fragments
Android App Development - 06 FragmentsAndroid App Development - 06 Fragments
Android App Development - 06 FragmentsDiego Grancini
 
Android 101 - Introduction to Android Development
Android 101 - Introduction to Android DevelopmentAndroid 101 - Introduction to Android Development
Android 101 - Introduction to Android DevelopmentAndy Scherzinger
 
Android Fragment Pattern: Communication
Android Fragment Pattern: CommunicationAndroid Fragment Pattern: Communication
Android Fragment Pattern: Communicationzmontesd
 
Spinners, Adapters & Fragment Communication
Spinners, Adapters & Fragment CommunicationSpinners, Adapters & Fragment Communication
Spinners, Adapters & Fragment CommunicationCITSimon
 
Android Fragment-Awesome
Android Fragment-AwesomeAndroid Fragment-Awesome
Android Fragment-AwesomeGauntFace
 
Google I/O 2011, Android Honeycomb Highlights
Google I/O 2011, Android Honeycomb HighlightsGoogle I/O 2011, Android Honeycomb Highlights
Google I/O 2011, Android Honeycomb HighlightsRomain Guy
 
Screen orientations in android
Screen orientations in androidScreen orientations in android
Screen orientations in androidmanjakannar
 
Short Intro to Android Fragments
Short Intro to Android FragmentsShort Intro to Android Fragments
Short Intro to Android FragmentsJussi Pohjolainen
 
Android Training (Storing & Shared Preferences)
Android Training (Storing & Shared Preferences)Android Training (Storing & Shared Preferences)
Android Training (Storing & Shared Preferences)Khaled Anaqwa
 
Fragments notes powerpoint
Fragments notes powerpointFragments notes powerpoint
Fragments notes powerpointktyndall
 
Future of Smart phone in Bangladesh
Future of Smart phone in Bangladesh Future of Smart phone in Bangladesh
Future of Smart phone in Bangladesh nationalmobileapps
 

Andere mochten auch (20)

Android - Working with Fragments
Android - Working with FragmentsAndroid - Working with Fragments
Android - Working with Fragments
 
Mobile Application capacity building activities
Mobile Application capacity building activities Mobile Application capacity building activities
Mobile Application capacity building activities
 
Introduction to Android Fragments
Introduction to Android FragmentsIntroduction to Android Fragments
Introduction to Android Fragments
 
Android App Development - 06 Fragments
Android App Development - 06 FragmentsAndroid App Development - 06 Fragments
Android App Development - 06 Fragments
 
Android Location Api
Android Location ApiAndroid Location Api
Android Location Api
 
Play Store
Play StorePlay Store
Play Store
 
Listview
ListviewListview
Listview
 
GCM (push notification)
GCM (push notification)GCM (push notification)
GCM (push notification)
 
Database
DatabaseDatabase
Database
 
Android 101 - Introduction to Android Development
Android 101 - Introduction to Android DevelopmentAndroid 101 - Introduction to Android Development
Android 101 - Introduction to Android Development
 
Android Fragment Pattern: Communication
Android Fragment Pattern: CommunicationAndroid Fragment Pattern: Communication
Android Fragment Pattern: Communication
 
Fragment debugging
Fragment debuggingFragment debugging
Fragment debugging
 
Spinners, Adapters & Fragment Communication
Spinners, Adapters & Fragment CommunicationSpinners, Adapters & Fragment Communication
Spinners, Adapters & Fragment Communication
 
Android Fragment-Awesome
Android Fragment-AwesomeAndroid Fragment-Awesome
Android Fragment-Awesome
 
Google I/O 2011, Android Honeycomb Highlights
Google I/O 2011, Android Honeycomb HighlightsGoogle I/O 2011, Android Honeycomb Highlights
Google I/O 2011, Android Honeycomb Highlights
 
Screen orientations in android
Screen orientations in androidScreen orientations in android
Screen orientations in android
 
Short Intro to Android Fragments
Short Intro to Android FragmentsShort Intro to Android Fragments
Short Intro to Android Fragments
 
Android Training (Storing & Shared Preferences)
Android Training (Storing & Shared Preferences)Android Training (Storing & Shared Preferences)
Android Training (Storing & Shared Preferences)
 
Fragments notes powerpoint
Fragments notes powerpointFragments notes powerpoint
Fragments notes powerpoint
 
Future of Smart phone in Bangladesh
Future of Smart phone in Bangladesh Future of Smart phone in Bangladesh
Future of Smart phone in Bangladesh
 

Ähnlich wie Fragment

Fragmentation in android
Fragmentation in android Fragmentation in android
Fragmentation in android Esraa El Ghoul
 
Tk2323 lecture 6 fragment (new)
Tk2323 lecture 6   fragment (new)Tk2323 lecture 6   fragment (new)
Tk2323 lecture 6 fragment (new)MengChun Lam
 
Architecting Single Activity Applications (With or Without Fragments)
Architecting Single Activity Applications (With or Without Fragments)Architecting Single Activity Applications (With or Without Fragments)
Architecting Single Activity Applications (With or Without Fragments)Gabor Varadi
 
Android apps development
Android apps developmentAndroid apps development
Android apps developmentMonir Zzaman
 
11.11.2020 - Unit 5-3 ACTIVITY, MENU AND SQLITE DATABASE.pptx
11.11.2020 - Unit 5-3  ACTIVITY, MENU AND SQLITE DATABASE.pptx11.11.2020 - Unit 5-3  ACTIVITY, MENU AND SQLITE DATABASE.pptx
11.11.2020 - Unit 5-3 ACTIVITY, MENU AND SQLITE DATABASE.pptxMugiiiReee
 
深入淺出談Fragment
深入淺出談Fragment深入淺出談Fragment
深入淺出談Fragment毅 方
 
Android lifecycle
Android lifecycleAndroid lifecycle
Android lifecycleKumar
 
Lecture #4 activities &amp; fragments
Lecture #4  activities &amp; fragmentsLecture #4  activities &amp; fragments
Lecture #4 activities &amp; fragmentsVitali Pekelis
 
04 activities - Android
04   activities - Android04   activities - Android
04 activities - AndroidWingston
 
Threads handlers and async task, widgets - day8
Threads   handlers and async task, widgets - day8Threads   handlers and async task, widgets - day8
Threads handlers and async task, widgets - day8Utkarsh Mankad
 
Android Jumpstart Jfokus
Android Jumpstart JfokusAndroid Jumpstart Jfokus
Android Jumpstart JfokusLars Vogel
 
B2. activity and intent
B2. activity and intentB2. activity and intent
B2. activity and intentPERKYTORIALS
 
What's New in Android
What's New in AndroidWhat's New in Android
What's New in AndroidRobert Cooper
 
MD-IV-CH-ppt.ppt
MD-IV-CH-ppt.pptMD-IV-CH-ppt.ppt
MD-IV-CH-ppt.pptbharatt7
 

Ähnlich wie Fragment (20)

Fragmentation in android
Fragmentation in android Fragmentation in android
Fragmentation in android
 
Android development session 4 - Fragments
Android development   session 4 - FragmentsAndroid development   session 4 - Fragments
Android development session 4 - Fragments
 
Tk2323 lecture 6 fragment (new)
Tk2323 lecture 6   fragment (new)Tk2323 lecture 6   fragment (new)
Tk2323 lecture 6 fragment (new)
 
What the fragments
What the fragmentsWhat the fragments
What the fragments
 
Architecting Single Activity Applications (With or Without Fragments)
Architecting Single Activity Applications (With or Without Fragments)Architecting Single Activity Applications (With or Without Fragments)
Architecting Single Activity Applications (With or Without Fragments)
 
Lesson 4
Lesson 4Lesson 4
Lesson 4
 
fragments-activity.pptx
fragments-activity.pptxfragments-activity.pptx
fragments-activity.pptx
 
Android apps development
Android apps developmentAndroid apps development
Android apps development
 
11.11.2020 - Unit 5-3 ACTIVITY, MENU AND SQLITE DATABASE.pptx
11.11.2020 - Unit 5-3  ACTIVITY, MENU AND SQLITE DATABASE.pptx11.11.2020 - Unit 5-3  ACTIVITY, MENU AND SQLITE DATABASE.pptx
11.11.2020 - Unit 5-3 ACTIVITY, MENU AND SQLITE DATABASE.pptx
 
深入淺出談Fragment
深入淺出談Fragment深入淺出談Fragment
深入淺出談Fragment
 
Android lifecycle
Android lifecycleAndroid lifecycle
Android lifecycle
 
Lecture #4 activities &amp; fragments
Lecture #4  activities &amp; fragmentsLecture #4  activities &amp; fragments
Lecture #4 activities &amp; fragments
 
04 activities - Android
04   activities - Android04   activities - Android
04 activities - Android
 
Threads handlers and async task, widgets - day8
Threads   handlers and async task, widgets - day8Threads   handlers and async task, widgets - day8
Threads handlers and async task, widgets - day8
 
Android Jumpstart Jfokus
Android Jumpstart JfokusAndroid Jumpstart Jfokus
Android Jumpstart Jfokus
 
Android 3
Android 3Android 3
Android 3
 
B2. activity and intent
B2. activity and intentB2. activity and intent
B2. activity and intent
 
What's New in Android
What's New in AndroidWhat's New in Android
What's New in Android
 
Android
AndroidAndroid
Android
 
MD-IV-CH-ppt.ppt
MD-IV-CH-ppt.pptMD-IV-CH-ppt.ppt
MD-IV-CH-ppt.ppt
 

Mehr von nationalmobileapps (10)

Android Sensor
Android SensorAndroid Sensor
Android Sensor
 
Ad Mob
Ad MobAd Mob
Ad Mob
 
Broadcast Receiver
Broadcast ReceiverBroadcast Receiver
Broadcast Receiver
 
Google Map V2
Google Map V2Google Map V2
Google Map V2
 
Activity & Shared Preference
Activity & Shared PreferenceActivity & Shared Preference
Activity & Shared Preference
 
Intent
IntentIntent
Intent
 
Support Multiple Screen
Support Multiple ScreenSupport Multiple Screen
Support Multiple Screen
 
Android UI
Android UIAndroid UI
Android UI
 
Event Handling
Event HandlingEvent Handling
Event Handling
 
Project anatomy & hello world
Project anatomy & hello worldProject anatomy & hello world
Project anatomy & hello world
 

Kürzlich hochgeladen

This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 

Kürzlich hochgeladen (20)

This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 

Fragment

  • 2. Fragment • An activity is a container for views • When you have a larger screen device than a phone –like a tablet it can look too simple to use phone interface here. •  Fragments • Mini-activities, each with its own set of views • One or more fragments can be embedded in an Activity • You can do this dynamically as a function of the device type (tablet or not) or orientation
  • 3. Fragment Idea •  Fragments • Mini-activities, each with its own set of views • One or more fragments can be embedded in an Activity • You can do this dynamically as a function of the device type (tablet or not) or orientation You might decide to run a tablet in portrait mode with the handset model of only one fragment in an Activity
  • 4. Fragment • 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. • You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities).
  • 5. Fragment Lifecycle • Fragment in an Activity---Activity Lifecyle influences – Activity paused  all its fragments paused – Activity destroyed  all its fragments paused – Activity running  manipulate each fragment independently. • Fragment transaction add, remove, etc. – adds it to a back stack that's managed by the activity— each back stack entry in the activity is a record of the fragment transaction that occurred. – The back stack allows the user to reverse a fragment transaction (navigate backwards), by pressing the Back button.
  • 6. Fragment inside Activity • it lives in a ViewGroup inside the activity's view hierarchy • fragment has its own view layout. • via XML: Insert a fragment into your activity layout by declaring the fragment in the activity's layout file, as a <fragment> element, • via CODE: from your application code by adding it to an existing ViewGroup. • you may also use a fragment without its own UI as an invisible worker for the activity.
  • 7. Fragment – extend a Fragment class • via CODE: extend android.app.Fragment OR one of its subclasses (DialogFragment, ListFragment, PreferenceFragment, WebViewFragment ) • IMPORTANT: must include a public empty constructor. The framework will often re-instantiate a fragment class when needed, in particular during state restore, and needs to be able to find this constructor to instantiate it. If the empty constructor is not available, a runtime exception will occur in some cases during state restore. • CALL Back functions (like Activity) : examples onCreate(), onStart(), onPause(), and onStop().
  • 8. Fragment methods (callback functions) • onAttach(Activity) called once the fragment is associated with its activity. • onCreate(Bundle) called to do initial creation of the fragment. • onCreateView(LayoutInflater, ViewGroup, Bundle) creates and returns the view hierarchy associated with the fragment. • onActivityCreated(Bundle) tells the fragment that its activity has completed its own Activity.onCreaate. • onStart() makes the fragment visible to the user (based on its containing activity being started). • onResume() makes the fragment interacting with the user (based on its containing activity being resumed).
  • 9. Fragment methods (callback functions) As a fragment is no longer being used, it goes through a reverse series of callbacks: • onPause() fragment is no longer interacting with the user either because its activity is being paused or a fragment operation is modifying it in the activity. • onStop() fragment is no longer visible to the user either because its activity is being stopped or a fragment operation is modifying it in the activity. • onDestroyView() allows the fragment to clean up resources associated with its View. • onDestroy() called to do final cleanup of the fragment's state. • onDetach() called immediately prior to the fragment no longer being associated with its activity.
  • 10. Create your own Fragment class or use known sub-classes • DialogFragment Displays a floating dialog. Using this class to create a dialog is a good alternative to using the dialog helper methods in the Activity class, because you can incorporate a fragment dialog into the back stack of fragments managed by the activity, allowing the user to return to a dismissed fragment. • ListFragment Displays a list of items that are managed by an adapter (such as a SimpleCursorAdapter), similar to ListActivity. It provides several methods for managing a list view, such as the onListItemClick() callback to handle click events. • PreferenceFragment Displays a hierarchy of Preference objects as a list, similar to PreferenceActivity. This is useful when creating a "settings" activity for your application.
  • 11. Fragments and their UI • Most fragments will have a UI • Will have its own layout • you must implement the onCreateView() callback method, which the Android system calls when it's time for the fragment to draw its layout. Your implementation of this method must return a View that is the root of your fragment's layout.
  • 12. Fragments and their UI – onCreateView() using XML • Can implement onCreateView using XML public static class ExampleFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.example_fragment, container, false); } } Bundle that provides data about the previous instance of the fragment, if the fragment is being resumed Have example_fragment.xml file that contains the layout This will be contained in resource layout folder. Activity parent’s ViewGroup
  • 13. OPTION1 –adding to an Activity via Activity layout XML. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <fragment android:name="com.example.news.ArticleListFragment" android:id="@+id/list" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" /> <fragment android:name="com.example.news.ArticleReaderFragment" android:id="@+id/viewer" android:layout_weight="2" android:layout_width="0dp" android:layout_height="match_parent" /> </LinearLayout> 2 fragment classes Need unique ids for each so system can restore the fragment if the activity is restarted
  • 14. OPTION2 –creating and adding to an Activity via CODE. /*Inside Activity Code where you want to add Fragment (dynamically anywhere or in onCreate() callback) */ //get FragmentTransaction associated with this Activity FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); //Create instance of your Fragment ExampleFragment fragment = new ExampleFragment(); This points to the Activity ViewGroup in which the fragment should be placed, specified by resource ID //Add Fragment instance to your Activity fragmentTransaction.add(R.id.fragment_container, fragment); fragmentTransaction.commit();
  • 15. OPTION 3- Adding Fragment that has NO UI using Code • use a fragment to provide a background behavior for the activity without presenting additional UI. • use add(Fragment, String) (supplying a unique string "tag" for the fragment, rather than a view ID). – it's not associated with a view in the activity layout, it does not receive a call to onCreateView(). So you don't need to implement that method. • If you want to get the fragment from the activity later, you need to use findFragmentByTag(). • For an example activity that uses a fragment as a background worker, without a UI, see the FragmentRetainInstance.java sample. • STOP AND LOOK AT EXAMPLE ON OUR OUTLINE!!!!!!
  • 16. Managing Fragments FragmentManager methods: • Get fragments that exist in Activity = – findFragmentById() (for fragments that provide a UI in the activity layout) – findFragmentByTag() (for fragments that do or don't provide a UI). • Pop fragments off the back stack, – popBackStack() (simulating a Back command by the user). • Register a listener for changes to the back stack, – addOnBackStackChangedListener().
  • 17. Fragment Transactions – adding, removing and replacing dynamically // Create new fragment and transaction Fragment newFragment = new ExampleFragment(); FragmentTransaction transaction getFragmentManager().beginTransaction(); // Replace whatever is in the fragment_container view with this fragment // and add the transaction to the back stack transaction.replace(R.id.fragment_container, newFragment); transaction.addToBackStack(null); // Commit the transaction transaction.commit(); newFragment replaces whatever fragment (if any) is currently in the layout container identified by the R.id.fragment_container If you do not call addToBackStack() when you perform a transaction that removes a fragment, then that fragment is destroyed when the transaction is committed and the user cannot navigate back to it. Whereas, if you do call addToBackStack() when removing a fragment, then the fragment is stopped and will be resumed if the user navigates back.
  • 18. Let’s Make a Fragment Project
  • 19. Lets Create a new project Fragment Basics Which Main Activity extends Fragment Activity
  • 24. HeadlinesFragment.java  The container Activity must implement this interface “OnHeadlineSelectedListener mCallback;” so the fragment can deliver messages
  • 26. onListItemClick()  Notify the parent activity of selected item  Set the item as checked to be highlighted when in two-pane layout
  • 27. ArticalFragment.java  If activity recreated (such as from screen rotate), restore the previous article selection set by onSaveInstanceState().  Inflate the layout for this fragment
  • 28. Article Fragment OnStart()  During startup, check if there are arguments passed to the fragment.  Set article based on argument passed in
  • 29. Update ArticleView(int position) • Set Article on TextView
  • 30. Now Back in MainActivity In onCreate() • Check whether the activity is using the layout version with the fragment_container FrameLayout. If so, we must add the first fragment • Create an instance of HeadlinesFragment • In case this activity was started with special instructions from an Intent, pass the Intent's extras to the fragment as arguments • Add the fragment to the 'fragment_container' FrameLayout
  • 31.
  • 32. In onArticleSelected(int position) • Capture the article fragment from the activity layout • If article fragment is available, we're in two-pane layout then Call a method in the ArticleFragment to update its content • If the fragment is not available, we're in the one-pane layout and must swap fragments Create fragment and give it an argument for the selected article • Replace whatever is in the fragment_container view with this fragment, and add the transaction to the back stack so the user can navigate back • Commit the transaction
  • 33.