SlideShare una empresa de Scribd logo
1 de 13
Mobile Application Development
FragmentActivity
1
Introduction
• Creating a dynamic and multi-pane user interface on
Android, need to encapsulate UI components and
activity behaviors into modules that you can swap into
and out of your activities.
• Fragment class can be used to create these modules,
which behaves somewhat like a nested activity that
can define its own layout and manage its own
lifecycle.
– It represents a behavior or a portion of user interface in
an Activity.
2
Introduction
• Developer can combine multiple fragments in a single
activity to build a multi-pane UI and reuse a fragment
in multiple activities.
– Fragment can be considered as a modular section of an
activity, which has its own lifecycle, receives its own
input events
– Fragment can be added or removed while the activity is
running
– Fragment introduced primarily to support more
dynamic and flexible UI designs on large screens, such
as tablets.
3
Introduction
4
Fragment Support Library
• The Support Library provides a version of the
Fragment APIs that you can use on Android 1.6 (API
level 4) and higher.
– Adding Support library to project
• Right click-> Android tools -> Add Support Library
– To be sure that you don't accidentally use new APIs on
an older system version, import the Fragment class and
related APIs from the android.support.v4.app package:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
5
Using Fragments
• The main activity must extends the FragmentActivity class
• The main activity’s layout should has a space, ViewGroup,
to display the fragments
– If there is more than one fragment appropriate way must be
used to call these fragments
• The fragment activity must extends the Fragment class
– Also all the other fragment activities too.
• Don’t forget that the fragment activity has its own
lifecycle.
6
Using Fragments
• In the MainActivity, do the following steps:
– Create a FragmentManager “fmgr"
• returned by getSupportFragmentManager()
– Create a FragmentTransaction “ftrans”
• returned by fmgr. beginTransaction();
– Add fragment object to FragmentTransaction
• ftrans.add(R.id.fragContainer, FragObj);
– Commit the FragmentTransaction to start the fragment.
• ftrans.commit();
7
Using Fragments
MainActivity
<LinearLayout …>
<LinearLayout
android:layout_weight="1"
android:layout_width="0dp">
<Button
android:id="@+id/btnFrag00"
android:text="Frag 00"
android:onClick="selectFragment"
/>
</LinearLayout>
<!-- the fragment container -->
<LinearLayout
android:id="@+id/fragContainer"
android:layout_weight="3"
android:layout_width="0dp"
…>
</LinearLayout>
</LinearLayout>
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fmgr =
getSupportFragmentManager();
FragmentTransaction ftrans =
fmgr.beginTransaction();
StartFragment startFrag = new StartFragment();
ftrans.add(R.id.fragContainer, startFrag);
ftrans.commit();
}
//handling fragments switching by using
//selectFragment method
} 8
Using Fragments
fragmentActivity
<LinearLayout
android:layout_height="…"
android:layout_width="...“
android:orientation="…" >
< TextView
android:id="@+id/txtV"
android:text="Frag 00"
android:onClick="selectFragment"
/>
…
…
</LinearLayout>
public class StartFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_start,
container, false);
}
} 9
onCreateView() is the only method that
needed in order to get a fragment
running.
Handling fragments switching
public void selectFragment(View v){
Fragment newFrag = new Fragment();
if(v == findViewById(R.id.btnFrag00))
newFrag = new Fragment00();
else if(v == findViewById(R.id.btnFrag01))
newFrag = new Fragment01();
else if(v == findViewById(R.id.btnFrag02))
newFrag = new Fragment02();
else if(v == findViewById(R.id.btnStartFrag))
newFrag = new StartFragment();
//switching the fragment
FragmentTransaction trans = getSupportFragmentManager().beginTransaction();
trans.replace(R.id.fragContainer,newFrag);
trans.addToBackStack(null);//used to put the previous fragment in pause mode
trans.commit();
} 10
Using XML fragment attribute
• The XML fragment attribute can be used to represent
the two or more fragments together in an activity.
11
<fragment
android:id="@+id/frag_list"
android:layout_weight="1"
android:layout_height="match_parent"
class="edu.itf.usingfragments.ListFrag"
/>
<fragment
android:id="@+id/frag_details"
android:layout_weight="1"
android:layout_height="match_parent"
class="edu.itf.usingfragments.DetailFrag"
/>
public class ListFrag extends ListFragment {
@Override
public void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
String[] positions = {"Dean", "ViceDean",
"CS", "IS", "MW" };
setListAdapter(…);
}
@Override
public void onListItemClick(ListView l, View v,
int position, long id) {
String selectedItem = (String)
getListAdapter().getItem(position);
DetailFrag frag = (DetailFrag)
getFragmentManager().
findFragmentById(R.id.frag_details);
if (frag != null && frag.isInLayout()) {
frag.setText(getPerson(selectedItem));
}
}
private String getPerson(String pos) {
if (pos.equals("Dean"))
return "Dr. Tawfiq";
if (pos.equals("ViceDean"))
return "Dr. Ribhi";
if (pos.equals("CS"))
return "Dr. Ashraf";
if (pos.equals("IS"))
return "Mr. Ehab";
if (pos.equals("MW"))
return "Mr. Ramzi";
return "???";
}
12
Assignment
• How to get/pass data from/to the fragment.
13

Más contenido relacionado

La actualidad más candente

Android UI Testing with uiautomator
Android UI Testing with uiautomatorAndroid UI Testing with uiautomator
Android UI Testing with uiautomatorJana Moudrá
 
iOSDevCamp 2012 - FilterKit Pitch
iOSDevCamp 2012 - FilterKit PitchiOSDevCamp 2012 - FilterKit Pitch
iOSDevCamp 2012 - FilterKit PitchAlexa Andrzejewski
 
Using Dagger in a Clean Architecture project
Using Dagger in a Clean Architecture projectUsing Dagger in a Clean Architecture project
Using Dagger in a Clean Architecture projectFabio Collini
 
[Android] DI in multimodule application
[Android] DI in multimodule application[Android] DI in multimodule application
[Android] DI in multimodule applicationOleg Mazhukin
 
Reuse features in Android applications
Reuse features in Android applicationsReuse features in Android applications
Reuse features in Android applicationsRomain Rochegude
 
Advance UIAutomator : Documentaion
Advance UIAutomator : DocumentaionAdvance UIAutomator : Documentaion
Advance UIAutomator : DocumentaionRaman Gowda Hullur
 
Dependency injection using dagger2
Dependency injection using dagger2Dependency injection using dagger2
Dependency injection using dagger2Javad Hashemi
 

La actualidad más candente (10)

Android UI Testing with uiautomator
Android UI Testing with uiautomatorAndroid UI Testing with uiautomator
Android UI Testing with uiautomator
 
iOSDevCamp 2012 - FilterKit Pitch
iOSDevCamp 2012 - FilterKit PitchiOSDevCamp 2012 - FilterKit Pitch
iOSDevCamp 2012 - FilterKit Pitch
 
Using Dagger in a Clean Architecture project
Using Dagger in a Clean Architecture projectUsing Dagger in a Clean Architecture project
Using Dagger in a Clean Architecture project
 
Dagger2 Intro
Dagger2 IntroDagger2 Intro
Dagger2 Intro
 
[Android] DI in multimodule application
[Android] DI in multimodule application[Android] DI in multimodule application
[Android] DI in multimodule application
 
Reuse features in Android applications
Reuse features in Android applicationsReuse features in Android applications
Reuse features in Android applications
 
UIAutomator
UIAutomatorUIAutomator
UIAutomator
 
Advance UIAutomator : Documentaion
Advance UIAutomator : DocumentaionAdvance UIAutomator : Documentaion
Advance UIAutomator : Documentaion
 
Espresso
EspressoEspresso
Espresso
 
Dependency injection using dagger2
Dependency injection using dagger2Dependency injection using dagger2
Dependency injection using dagger2
 

Destacado

Curriculum Cc inntegra - Marzo 2011
Curriculum Cc inntegra - Marzo 2011Curriculum Cc inntegra - Marzo 2011
Curriculum Cc inntegra - Marzo 2011CC Inntegra
 
Historia De La Compu Mango
Historia De La Compu MangoHistoria De La Compu Mango
Historia De La Compu Mangovianneyminor
 
Resolution On Global Warming Action - Community Christian Church, Tempe, Ariz...
Resolution On Global Warming Action - Community Christian Church, Tempe, Ariz...Resolution On Global Warming Action - Community Christian Church, Tempe, Ariz...
Resolution On Global Warming Action - Community Christian Church, Tempe, Ariz...Z2P
 
Quick Resource Overview - Green Churches and Earth Care
Quick Resource Overview - Green Churches and Earth Care  Quick Resource Overview - Green Churches and Earth Care
Quick Resource Overview - Green Churches and Earth Care Z2P
 
IT Security - Guidelines
IT Security - GuidelinesIT Security - Guidelines
IT Security - GuidelinesPedro Espinosa
 

Destacado (7)

Curriculum Cc inntegra - Marzo 2011
Curriculum Cc inntegra - Marzo 2011Curriculum Cc inntegra - Marzo 2011
Curriculum Cc inntegra - Marzo 2011
 
Historia De La Compu Mango
Historia De La Compu MangoHistoria De La Compu Mango
Historia De La Compu Mango
 
Resolution On Global Warming Action - Community Christian Church, Tempe, Ariz...
Resolution On Global Warming Action - Community Christian Church, Tempe, Ariz...Resolution On Global Warming Action - Community Christian Church, Tempe, Ariz...
Resolution On Global Warming Action - Community Christian Church, Tempe, Ariz...
 
Day 2, session 9, melissa fach
Day 2, session 9, melissa fachDay 2, session 9, melissa fach
Day 2, session 9, melissa fach
 
5750 dalmagro sandra
5750 dalmagro sandra5750 dalmagro sandra
5750 dalmagro sandra
 
Quick Resource Overview - Green Churches and Earth Care
Quick Resource Overview - Green Churches and Earth Care  Quick Resource Overview - Green Churches and Earth Care
Quick Resource Overview - Green Churches and Earth Care
 
IT Security - Guidelines
IT Security - GuidelinesIT Security - Guidelines
IT Security - Guidelines
 

Similar a FragmentActivity and Fragments for Dynamic UIs

Android design patterns
Android design patternsAndroid design patterns
Android design patternsPlatty Soft
 
[PBO] Pertemuan 12 - Pemrograman Android
[PBO] Pertemuan 12 - Pemrograman Android[PBO] Pertemuan 12 - Pemrograman Android
[PBO] Pertemuan 12 - Pemrograman Androidrizki adam kurniawan
 
Lecture #4 activities &amp; fragments
Lecture #4  activities &amp; fragmentsLecture #4  activities &amp; fragments
Lecture #4 activities &amp; fragmentsVitali Pekelis
 
Android lifecycle
Android lifecycleAndroid lifecycle
Android lifecycleKumar
 
Android - Open Source Bridge 2011
Android - Open Source Bridge 2011Android - Open Source Bridge 2011
Android - Open Source Bridge 2011sullis
 
MD-IV-CH-ppt.ppt
MD-IV-CH-ppt.pptMD-IV-CH-ppt.ppt
MD-IV-CH-ppt.pptbharatt7
 
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
 
Dori waldman android _course
Dori waldman android _courseDori waldman android _course
Dori waldman android _courseDori Waldman
 
Fragments In Android
Fragments In AndroidFragments In Android
Fragments In AndroidDivyaKS12
 
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
 
Dori waldman android _course_2
Dori waldman android _course_2Dori waldman android _course_2
Dori waldman android _course_2Dori Waldman
 
Integrate Shindig with Joomla
Integrate Shindig with JoomlaIntegrate Shindig with Joomla
Integrate Shindig with JoomlaAnand Sharma
 
Introduction to Android Development
Introduction to Android DevelopmentIntroduction to Android Development
Introduction to Android DevelopmentAly Abdelkareem
 
B2. activity and intent
B2. activity and intentB2. activity and intent
B2. activity and intentPERKYTORIALS
 
Tk2323 lecture 6 fragment (new)
Tk2323 lecture 6   fragment (new)Tk2323 lecture 6   fragment (new)
Tk2323 lecture 6 fragment (new)MengChun Lam
 
Android Jumpstart Jfokus
Android Jumpstart JfokusAndroid Jumpstart Jfokus
Android Jumpstart JfokusLars Vogel
 

Similar a FragmentActivity and Fragments for Dynamic UIs (20)

Fragment
Fragment Fragment
Fragment
 
Android design patterns
Android design patternsAndroid design patterns
Android design patterns
 
[PBO] Pertemuan 12 - Pemrograman Android
[PBO] Pertemuan 12 - Pemrograman Android[PBO] Pertemuan 12 - Pemrograman Android
[PBO] Pertemuan 12 - Pemrograman Android
 
fragments-activity.pptx
fragments-activity.pptxfragments-activity.pptx
fragments-activity.pptx
 
Lecture #4 activities &amp; fragments
Lecture #4  activities &amp; fragmentsLecture #4  activities &amp; fragments
Lecture #4 activities &amp; fragments
 
Android lifecycle
Android lifecycleAndroid lifecycle
Android lifecycle
 
Android - Open Source Bridge 2011
Android - Open Source Bridge 2011Android - Open Source Bridge 2011
Android - Open Source Bridge 2011
 
Android
AndroidAndroid
Android
 
Lesson 4
Lesson 4Lesson 4
Lesson 4
 
MD-IV-CH-ppt.ppt
MD-IV-CH-ppt.pptMD-IV-CH-ppt.ppt
MD-IV-CH-ppt.ppt
 
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
 
Dori waldman android _course
Dori waldman android _courseDori waldman android _course
Dori waldman android _course
 
Fragments In Android
Fragments In AndroidFragments In Android
Fragments In Android
 
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
 
Dori waldman android _course_2
Dori waldman android _course_2Dori waldman android _course_2
Dori waldman android _course_2
 
Integrate Shindig with Joomla
Integrate Shindig with JoomlaIntegrate Shindig with Joomla
Integrate Shindig with Joomla
 
Introduction to Android Development
Introduction to Android DevelopmentIntroduction to Android Development
Introduction to Android Development
 
B2. activity and intent
B2. activity and intentB2. activity and intent
B2. activity and intent
 
Tk2323 lecture 6 fragment (new)
Tk2323 lecture 6   fragment (new)Tk2323 lecture 6   fragment (new)
Tk2323 lecture 6 fragment (new)
 
Android Jumpstart Jfokus
Android Jumpstart JfokusAndroid Jumpstart Jfokus
Android Jumpstart Jfokus
 

Último

Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 

Último (20)

Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 

FragmentActivity and Fragments for Dynamic UIs

  • 2. Introduction • Creating a dynamic and multi-pane user interface on Android, need to encapsulate UI components and activity behaviors into modules that you can swap into and out of your activities. • Fragment class can be used to create these modules, which behaves somewhat like a nested activity that can define its own layout and manage its own lifecycle. – It represents a behavior or a portion of user interface in an Activity. 2
  • 3. Introduction • Developer can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. – Fragment can be considered as a modular section of an activity, which has its own lifecycle, receives its own input events – Fragment can be added or removed while the activity is running – Fragment introduced primarily to support more dynamic and flexible UI designs on large screens, such as tablets. 3
  • 5. Fragment Support Library • The Support Library provides a version of the Fragment APIs that you can use on Android 1.6 (API level 4) and higher. – Adding Support library to project • Right click-> Android tools -> Add Support Library – To be sure that you don't accidentally use new APIs on an older system version, import the Fragment class and related APIs from the android.support.v4.app package: import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; 5
  • 6. Using Fragments • The main activity must extends the FragmentActivity class • The main activity’s layout should has a space, ViewGroup, to display the fragments – If there is more than one fragment appropriate way must be used to call these fragments • The fragment activity must extends the Fragment class – Also all the other fragment activities too. • Don’t forget that the fragment activity has its own lifecycle. 6
  • 7. Using Fragments • In the MainActivity, do the following steps: – Create a FragmentManager “fmgr" • returned by getSupportFragmentManager() – Create a FragmentTransaction “ftrans” • returned by fmgr. beginTransaction(); – Add fragment object to FragmentTransaction • ftrans.add(R.id.fragContainer, FragObj); – Commit the FragmentTransaction to start the fragment. • ftrans.commit(); 7
  • 8. Using Fragments MainActivity <LinearLayout …> <LinearLayout android:layout_weight="1" android:layout_width="0dp"> <Button android:id="@+id/btnFrag00" android:text="Frag 00" android:onClick="selectFragment" /> </LinearLayout> <!-- the fragment container --> <LinearLayout android:id="@+id/fragContainer" android:layout_weight="3" android:layout_width="0dp" …> </LinearLayout> </LinearLayout> public class MainActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FragmentManager fmgr = getSupportFragmentManager(); FragmentTransaction ftrans = fmgr.beginTransaction(); StartFragment startFrag = new StartFragment(); ftrans.add(R.id.fragContainer, startFrag); ftrans.commit(); } //handling fragments switching by using //selectFragment method } 8
  • 9. Using Fragments fragmentActivity <LinearLayout android:layout_height="…" android:layout_width="...“ android:orientation="…" > < TextView android:id="@+id/txtV" android:text="Frag 00" android:onClick="selectFragment" /> … … </LinearLayout> public class StartFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_start, container, false); } } 9 onCreateView() is the only method that needed in order to get a fragment running.
  • 10. Handling fragments switching public void selectFragment(View v){ Fragment newFrag = new Fragment(); if(v == findViewById(R.id.btnFrag00)) newFrag = new Fragment00(); else if(v == findViewById(R.id.btnFrag01)) newFrag = new Fragment01(); else if(v == findViewById(R.id.btnFrag02)) newFrag = new Fragment02(); else if(v == findViewById(R.id.btnStartFrag)) newFrag = new StartFragment(); //switching the fragment FragmentTransaction trans = getSupportFragmentManager().beginTransaction(); trans.replace(R.id.fragContainer,newFrag); trans.addToBackStack(null);//used to put the previous fragment in pause mode trans.commit(); } 10
  • 11. Using XML fragment attribute • The XML fragment attribute can be used to represent the two or more fragments together in an activity. 11 <fragment android:id="@+id/frag_list" android:layout_weight="1" android:layout_height="match_parent" class="edu.itf.usingfragments.ListFrag" /> <fragment android:id="@+id/frag_details" android:layout_weight="1" android:layout_height="match_parent" class="edu.itf.usingfragments.DetailFrag" />
  • 12. public class ListFrag extends ListFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String[] positions = {"Dean", "ViceDean", "CS", "IS", "MW" }; setListAdapter(…); } @Override public void onListItemClick(ListView l, View v, int position, long id) { String selectedItem = (String) getListAdapter().getItem(position); DetailFrag frag = (DetailFrag) getFragmentManager(). findFragmentById(R.id.frag_details); if (frag != null && frag.isInLayout()) { frag.setText(getPerson(selectedItem)); } } private String getPerson(String pos) { if (pos.equals("Dean")) return "Dr. Tawfiq"; if (pos.equals("ViceDean")) return "Dr. Ribhi"; if (pos.equals("CS")) return "Dr. Ashraf"; if (pos.equals("IS")) return "Mr. Ehab"; if (pos.equals("MW")) return "Mr. Ramzi"; return "???"; } 12
  • 13. Assignment • How to get/pass data from/to the fragment. 13

Notas del editor

  1. tablet&apos;s screen is much larger than that of a handset, there&apos;s more room to combine and interchange UI components.