SlideShare une entreprise Scribd logo
1  sur  18
Building	
  a	
  Dynamic	
  UI	
  with	
  
Fragments	
  
Jussi	
  Pohjolainen	
  
About	
  Fragments	
  
•  Fragments	
  are	
  “subac'vity”;	
  modular	
  sec>on	
  
inside	
  the	
  ac>vity.	
  
•  You	
  can	
  add	
  and	
  remove	
  fragments	
  at	
  
run>me	
  
•  Fragment	
  has	
  it’s	
  own	
  UI	
  (.xml	
  file)	
  
•  Feature	
  that	
  came	
  in	
  API	
  Level	
  11	
  -­‐>	
  need	
  to	
  
have	
  support	
  library	
  if	
  targe>ng	
  older	
  devices	
  
Design	
  Philosophy	
  
Crea>ng	
  a	
  Fragment	
  
•  Subclass	
  of	
  Fragment	
  
•  Implement	
  lifecycle	
  methods	
  that	
  are	
  similar	
  to	
  
Ac>vity’s.	
  
–  onCreate, onStart, onPause, onStop..
•  Implement	
  at	
  least	
  
–  onCreate
•  Ini>alize	
  essen>al	
  components	
  
–  onCreateView
•  Return	
  View	
  –	
  object	
  that	
  is	
  the	
  root	
  of	
  your	
  fragment’s	
  layout	
  
–  onPause
•  User	
  is	
  leaving	
  the	
  fragment	
  
Example	
  Fragment:	
  MainActivity.java
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.main);
}
}
Example	
  Fragment:	
  main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<fragment
android:id="@+id/fragment1"
android:name="com.example.fragmentexample.LeftFragment"
android:layout_width="0dp"
android:layout_weight="0.5"
android:layout_height="match_parent" />
<fragment
android:id="@+id/fragment2"
android:name="com.example.fragmentexample.RightFragment"
android:layout_width="0dp"
android:layout_weight="0.5"
android:layout_height="match_parent" />
</LinearLayout>
Example	
  Fragment:	
  LeftFragment.java
public class LeftFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Button tv = new Button(getActivity());
tv.setText("left!");
return tv;
}
}
Example	
  Fragment:	
  RightFragment.java
public class RightFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Button tv = new Button(getActivity());
tv.setText("right!");
return tv;
}
}
Fragment	
  may	
  hold	
  XML	
  too!	
  
public class RightFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Let’s remove these
// Button tv = new Button(getActivity());
// tv.setText("right!");
// return tv;
// Creates Java object from the given XML file.
View view = inflater.inflate(R.layout.right_fragment, // The xml file
container,
false);
return view;
}
}
FragmentManager
•  FragmentManager	
  class	
  provides	
  methods	
  
that	
  allow	
  you	
  to	
  add,	
  remove	
  and	
  replace	
  
fragments	
  to	
  on	
  ac>vity	
  at	
  run>me.	
  
•  Don’t	
  add	
  fragments	
  to	
  .xml,	
  but	
  perform	
  
transac>on	
  in	
  Java	
  
•  See:	
  	
  
–  https://developer.android.com/training/basics/
fragments/fragment-ui.html
FragmentManager:	
  	
  
GeYng	
  reference	
  to	
  fragments	
  
// Activity has getFragmentManager() – method!
FragmentManager fragmentManager = getFragmentManager();
ChooseTitleFragment ctf =
(ChooseTitleFragment)
fragmentManager.findFragmentById(R.id.choose);
Communica>on	
  Between	
  Fragments	
  
•  Build	
  each	
  Fragment	
  UI	
  as	
  separate!	
  
•  Do	
  Fragment	
  -­‐>	
  Fragment	
  communica>on	
  
through	
  Ac>vity	
  
•  Fragment	
  A	
  -­‐>	
  Ac8vity	
  
– Use	
  your	
  own	
  interface,	
  ac>vity	
  can	
  be	
  whatever	
  
•  Ac8vity	
  -­‐>	
  Fragment	
  B	
  
– Use	
  FragmentManager	
  to	
  get	
  a	
  reference	
  to	
  
Fragment	
  B	
  and	
  call	
  it’s	
  public	
  methods	
  
public class ButtonFragment extends Fragment {
// Helper interface for communicating with Activity
public interface OnButtonClickedListener {
public void buttonClicked();
}
// Host Activity is here
private OnButtonClickedListener callback;
// When creating this fragment, host activity must be given and it must
// implement OnButtonClickedListener interface. Method is called when fragment has
// been associated with activity. The Activity is passed here!
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
callback = (OnButtonClickedListener) activity;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Creates Java object from the given XML file.
View view = inflater.inflate(R.layout.button_fragment, // The xml file
container,
false);
Button sent = (Button) view.findViewById(R.id.button1);
// When button is clicked, call activity's buttonClicked method
sent.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
callback.buttonClicked();
}
});
return view;
}
}
Ac>vity	
  
public class MainActivity extends Activity implements
ButtonFragment.OnButtonClickedListener {
@Override
public void onCreate(Bundle b) {
super.onCreate(b);
// Holds ButtonFragment
setContentView(R.layout.main);
}
// This is called when button is pressed in the fragment!
@Override
public void buttonClicked() {
}
}
Basic	
  Idea:	
  How?	
  
Use	
  layout/	
  directories	
  
•  layout/main.xml	
  
– One	
  dim	
  layout	
  (holds	
  Fragment	
  A)	
  
•  layout-­‐land/main.xml	
  
– Two	
  dim	
  layout	
  (holds	
  Fragment	
  A	
  +	
  B)	
  
•  layout-­‐large/main.xml	
  
– Two	
  dim	
  layout	
  (holds	
  Fragment	
  A	
  +	
  B)	
  
public class MainActivity extends Activity implements ButtonFragment.OnButtonClickedListener {
@Override
public void onCreate(Bundle b) {
super.onCreate(b);
// Holds either two-dim or on-dim layout! hold either
// 1) left-pane or
// 2) left-pane and right-pane
setContentView(R.layout.main);
}
// This is called when button is pressed in the fragment!
@Override
public void buttonClicked() {
// Let's get a reference to the right fragment
RightPaneFragment rightPaneFragment = (RightPaneFragment) getFragmentManager()
.findFragmentById(R.id.right_fragment);
// If it's not accessible, we are in one-dim layout
if (rigthPaneFragment == null) {
startNewActivity();
} else {
updateRightPane();
}
}
private void startNewActivity() {
Intent showContent = new Intent(this, RightActivityPane.class); // This activity holds RightPaneFragment
startActivity(showContent);
}
private void updateRightPane(RightPaneFragment rightPaneFragment) {
rightPaneFragment.doSomething();
}
}

Contenu connexe

Tendances

Introduction to fragments in android
Introduction to fragments in androidIntroduction to fragments in android
Introduction to fragments in androidPrawesh Shrestha
 
Activities, Fragments, and Events
Activities, Fragments, and EventsActivities, Fragments, and Events
Activities, Fragments, and EventsHenry Osborne
 
Managing Activity Backstack
Managing Activity BackstackManaging Activity Backstack
Managing Activity Backstackrajdeep
 
Android App Development - 02 Activity and intent
Android App Development - 02 Activity and intentAndroid App Development - 02 Activity and intent
Android App Development - 02 Activity and intentDiego Grancini
 
Hi AndroidAnnotations
Hi AndroidAnnotationsHi AndroidAnnotations
Hi AndroidAnnotationsTsung-Yeh Lee
 
STYLISH FLOOR
STYLISH FLOORSTYLISH FLOOR
STYLISH FLOORABU HASAN
 
Advanced Dagger talk from 360andev
Advanced Dagger talk from 360andevAdvanced Dagger talk from 360andev
Advanced Dagger talk from 360andevMike Nakhimovich
 
A comprehensive guide on developing responsive and common react filter component
A comprehensive guide on developing responsive and common react filter componentA comprehensive guide on developing responsive and common react filter component
A comprehensive guide on developing responsive and common react filter componentKaty Slemon
 
Android basic 4 Navigation Drawer
Android basic 4 Navigation DrawerAndroid basic 4 Navigation Drawer
Android basic 4 Navigation DrawerEakapong Kattiya
 
Anton Minashkin Dagger 2 light
Anton Minashkin Dagger 2 lightAnton Minashkin Dagger 2 light
Anton Minashkin Dagger 2 lightMichael Pustovit
 
Intents in Android
Intents in AndroidIntents in Android
Intents in Androidma-polimi
 
Andriod dev toolbox part 2
Andriod dev toolbox  part 2Andriod dev toolbox  part 2
Andriod dev toolbox part 2Shem Magnezi
 
Annotation Processing
Annotation ProcessingAnnotation Processing
Annotation ProcessingJintin Lin
 
Android lifecycle
Android lifecycleAndroid lifecycle
Android lifecycleKumar
 
Button
ButtonButton
ButtonLwp Xd
 

Tendances (20)

Introduction to fragments in android
Introduction to fragments in androidIntroduction to fragments in android
Introduction to fragments in android
 
Activities, Fragments, and Events
Activities, Fragments, and EventsActivities, Fragments, and Events
Activities, Fragments, and Events
 
Fragments anyone
Fragments anyone Fragments anyone
Fragments anyone
 
Managing Activity Backstack
Managing Activity BackstackManaging Activity Backstack
Managing Activity Backstack
 
Android App Development - 02 Activity and intent
Android App Development - 02 Activity and intentAndroid App Development - 02 Activity and intent
Android App Development - 02 Activity and intent
 
Hi AndroidAnnotations
Hi AndroidAnnotationsHi AndroidAnnotations
Hi AndroidAnnotations
 
STYLISH FLOOR
STYLISH FLOORSTYLISH FLOOR
STYLISH FLOOR
 
Advanced Dagger talk from 360andev
Advanced Dagger talk from 360andevAdvanced Dagger talk from 360andev
Advanced Dagger talk from 360andev
 
Lab1-android
Lab1-androidLab1-android
Lab1-android
 
Android development session 2 - intent and activity
Android development   session 2 - intent and activityAndroid development   session 2 - intent and activity
Android development session 2 - intent and activity
 
A comprehensive guide on developing responsive and common react filter component
A comprehensive guide on developing responsive and common react filter componentA comprehensive guide on developing responsive and common react filter component
A comprehensive guide on developing responsive and common react filter component
 
Android basic 4 Navigation Drawer
Android basic 4 Navigation DrawerAndroid basic 4 Navigation Drawer
Android basic 4 Navigation Drawer
 
Android basic 2 UI Design
Android basic 2 UI DesignAndroid basic 2 UI Design
Android basic 2 UI Design
 
Android basic 3 Dialogs
Android basic 3 DialogsAndroid basic 3 Dialogs
Android basic 3 Dialogs
 
Anton Minashkin Dagger 2 light
Anton Minashkin Dagger 2 lightAnton Minashkin Dagger 2 light
Anton Minashkin Dagger 2 light
 
Intents in Android
Intents in AndroidIntents in Android
Intents in Android
 
Andriod dev toolbox part 2
Andriod dev toolbox  part 2Andriod dev toolbox  part 2
Andriod dev toolbox part 2
 
Annotation Processing
Annotation ProcessingAnnotation Processing
Annotation Processing
 
Android lifecycle
Android lifecycleAndroid lifecycle
Android lifecycle
 
Button
ButtonButton
Button
 

En vedette

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
 
Screen orientations in android
Screen orientations in androidScreen orientations in android
Screen orientations in androidmanjakannar
 
Android Fragment-Awesome
Android Fragment-AwesomeAndroid Fragment-Awesome
Android Fragment-AwesomeGauntFace
 
Laporan observasi rpp dan laboratorium
Laporan observasi rpp dan laboratoriumLaporan observasi rpp dan laboratorium
Laporan observasi rpp dan laboratoriumSamantars17
 
Exposicion de financiamientos
Exposicion de financiamientosExposicion de financiamientos
Exposicion de financiamientosAlita Orpe
 
εργασία: κριτήρια επιλογής, συνέπειες βιομηχανικής επανάστασης
εργασία: κριτήρια επιλογής, συνέπειες βιομηχανικής επανάστασηςεργασία: κριτήρια επιλογής, συνέπειες βιομηχανικής επανάστασης
εργασία: κριτήρια επιλογής, συνέπειες βιομηχανικής επανάστασηςπεντάλ σχολικό
 
Understanding Android Handling of Touch Events
Understanding Android Handling of Touch EventsUnderstanding Android Handling of Touch Events
Understanding Android Handling of Touch Eventsjensmohr
 
Android Security, Signing and Publishing
Android Security, Signing and PublishingAndroid Security, Signing and Publishing
Android Security, Signing and PublishingJussi Pohjolainen
 
Quick Intro to Android Development
Quick Intro to Android DevelopmentQuick Intro to Android Development
Quick Intro to Android DevelopmentJussi Pohjolainen
 
Android Http Connection and SAX Parsing
Android Http Connection and SAX ParsingAndroid Http Connection and SAX Parsing
Android Http Connection and SAX ParsingJussi Pohjolainen
 

En vedette (20)

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
 
Spinners, Adapters & Fragment Communication
Spinners, Adapters & Fragment CommunicationSpinners, Adapters & Fragment Communication
Spinners, Adapters & Fragment Communication
 
Screen orientations in android
Screen orientations in androidScreen orientations in android
Screen orientations in android
 
Android Fragment-Awesome
Android Fragment-AwesomeAndroid Fragment-Awesome
Android Fragment-Awesome
 
Baby talk 2
Baby talk 2Baby talk 2
Baby talk 2
 
Clases de noviembre 5 ños 1
Clases de noviembre 5 ños 1Clases de noviembre 5 ños 1
Clases de noviembre 5 ños 1
 
Laporan observasi rpp dan laboratorium
Laporan observasi rpp dan laboratoriumLaporan observasi rpp dan laboratorium
Laporan observasi rpp dan laboratorium
 
resume
resumeresume
resume
 
Exposicion de financiamientos
Exposicion de financiamientosExposicion de financiamientos
Exposicion de financiamientos
 
Great quotes of bruce lee
Great quotes of bruce leeGreat quotes of bruce lee
Great quotes of bruce lee
 
εργασία: κριτήρια επιλογής, συνέπειες βιομηχανικής επανάστασης
εργασία: κριτήρια επιλογής, συνέπειες βιομηχανικής επανάστασηςεργασία: κριτήρια επιλογής, συνέπειες βιομηχανικής επανάστασης
εργασία: κριτήρια επιλογής, συνέπειες βιομηχανικής επανάστασης
 
Understanding Android Handling of Touch Events
Understanding Android Handling of Touch EventsUnderstanding Android Handling of Touch Events
Understanding Android Handling of Touch Events
 
Android Security, Signing and Publishing
Android Security, Signing and PublishingAndroid Security, Signing and Publishing
Android Security, Signing and Publishing
 
Quick Intro to Android Development
Quick Intro to Android DevelopmentQuick Intro to Android Development
Quick Intro to Android Development
 
Responsive Web Site Design
Responsive Web Site DesignResponsive Web Site Design
Responsive Web Site Design
 
C# for Java Developers
C# for Java DevelopersC# for Java Developers
C# for Java Developers
 
Building Web Services
Building Web ServicesBuilding Web Services
Building Web Services
 
Android Essential Tools
Android Essential ToolsAndroid Essential Tools
Android Essential Tools
 
Android Http Connection and SAX Parsing
Android Http Connection and SAX ParsingAndroid Http Connection and SAX Parsing
Android Http Connection and SAX Parsing
 

Similaire à Short Intro to Android Fragments

深入淺出談Fragment
深入淺出談Fragment深入淺出談Fragment
深入淺出談Fragment毅 方
 
Fragments In Android
Fragments In AndroidFragments In Android
Fragments In AndroidDivyaKS12
 
Tk2323 lecture 6 fragment (new)
Tk2323 lecture 6   fragment (new)Tk2323 lecture 6   fragment (new)
Tk2323 lecture 6 fragment (new)MengChun Lam
 
android activity
android activityandroid activity
android activityDeepa Rani
 
Android development - Activities, Views & Intents
Android development - Activities, Views & IntentsAndroid development - Activities, Views & Intents
Android development - Activities, Views & IntentsLope Emano
 
Desbravando Web Components
Desbravando Web ComponentsDesbravando Web Components
Desbravando Web ComponentsMateus Ortiz
 
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
 
04 activities - Android
04   activities - Android04   activities - Android
04 activities - AndroidWingston
 
Fragmentation in android
Fragmentation in android Fragmentation in android
Fragmentation in android Esraa El Ghoul
 
Enhance react app with patterns - part 1: higher order component
Enhance react app with patterns - part 1: higher order componentEnhance react app with patterns - part 1: higher order component
Enhance react app with patterns - part 1: higher order componentYao Nien Chung
 

Similaire à Short Intro to Android Fragments (20)

深入淺出談Fragment
深入淺出談Fragment深入淺出談Fragment
深入淺出談Fragment
 
What the fragments
What the fragmentsWhat the fragments
What the fragments
 
Fragments In Android
Fragments In AndroidFragments In Android
Fragments In Android
 
Tk2323 lecture 6 fragment (new)
Tk2323 lecture 6   fragment (new)Tk2323 lecture 6   fragment (new)
Tk2323 lecture 6 fragment (new)
 
Lesson 4
Lesson 4Lesson 4
Lesson 4
 
Android Basic Components
Android Basic ComponentsAndroid Basic Components
Android Basic Components
 
fragments-activity.pptx
fragments-activity.pptxfragments-activity.pptx
fragments-activity.pptx
 
android activity
android activityandroid activity
android activity
 
Android development - Activities, Views & Intents
Android development - Activities, Views & IntentsAndroid development - Activities, Views & Intents
Android development - Activities, Views & Intents
 
Swing_Introduction.ppt
Swing_Introduction.pptSwing_Introduction.ppt
Swing_Introduction.ppt
 
Desbravando Web Components
Desbravando Web ComponentsDesbravando Web Components
Desbravando Web Components
 
Lab3-Android
Lab3-AndroidLab3-Android
Lab3-Android
 
Gui
GuiGui
Gui
 
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)
 
04 activities - Android
04   activities - Android04   activities - Android
04 activities - Android
 
Fragmentation in android
Fragmentation in android Fragmentation in android
Fragmentation in android
 
Enhance react app with patterns - part 1: higher order component
Enhance react app with patterns - part 1: higher order componentEnhance react app with patterns - part 1: higher order component
Enhance react app with patterns - part 1: higher order component
 
Activity
ActivityActivity
Activity
 
Activity
ActivityActivity
Activity
 
Activity
ActivityActivity
Activity
 

Plus de Jussi Pohjolainen

libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferenceslibGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferencesJussi Pohjolainen
 
libGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationlibGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationJussi Pohjolainen
 
Intro to Building Android Games using libGDX
Intro to Building Android Games using libGDXIntro to Building Android Games using libGDX
Intro to Building Android Games using libGDXJussi Pohjolainen
 
Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript DevelopmentJussi Pohjolainen
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame AnimationJussi Pohjolainen
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame AnimationJussi Pohjolainen
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDXJussi Pohjolainen
 
Building Android games using LibGDX
Building Android games using LibGDXBuilding Android games using LibGDX
Building Android games using LibGDXJussi Pohjolainen
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesJussi Pohjolainen
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platformJussi Pohjolainen
 

Plus de Jussi Pohjolainen (20)

Moved to Speakerdeck
Moved to SpeakerdeckMoved to Speakerdeck
Moved to Speakerdeck
 
Java Web Services
Java Web ServicesJava Web Services
Java Web Services
 
Box2D and libGDX
Box2D and libGDXBox2D and libGDX
Box2D and libGDX
 
libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferenceslibGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and Preferences
 
libGDX: Tiled Maps
libGDX: Tiled MapslibGDX: Tiled Maps
libGDX: Tiled Maps
 
libGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationlibGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame Animation
 
Intro to Building Android Games using libGDX
Intro to Building Android Games using libGDXIntro to Building Android Games using libGDX
Intro to Building Android Games using libGDX
 
Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript Development
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
libGDX: Scene2D
libGDX: Scene2DlibGDX: Scene2D
libGDX: Scene2D
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
libGDX: User Input
libGDX: User InputlibGDX: User Input
libGDX: User Input
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDX
 
Building Android games using LibGDX
Building Android games using LibGDXBuilding Android games using LibGDX
Building Android games using LibGDX
 
Android Threading
Android ThreadingAndroid Threading
Android Threading
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platform
 
Intro to Asha UI
Intro to Asha UIIntro to Asha UI
Intro to Asha UI
 

Dernier

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 

Dernier (20)

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 

Short Intro to Android Fragments

  • 1. Building  a  Dynamic  UI  with   Fragments   Jussi  Pohjolainen  
  • 2. About  Fragments   •  Fragments  are  “subac'vity”;  modular  sec>on   inside  the  ac>vity.   •  You  can  add  and  remove  fragments  at   run>me   •  Fragment  has  it’s  own  UI  (.xml  file)   •  Feature  that  came  in  API  Level  11  -­‐>  need  to   have  support  library  if  targe>ng  older  devices  
  • 4. Crea>ng  a  Fragment   •  Subclass  of  Fragment   •  Implement  lifecycle  methods  that  are  similar  to   Ac>vity’s.   –  onCreate, onStart, onPause, onStop.. •  Implement  at  least   –  onCreate •  Ini>alize  essen>al  components   –  onCreateView •  Return  View  –  object  that  is  the  root  of  your  fragment’s  layout   –  onPause •  User  is  leaving  the  fragment  
  • 5. Example  Fragment:  MainActivity.java public class MainActivity extends Activity { @Override public void onCreate(Bundle b) { super.onCreate(b); setContentView(R.layout.main); } }
  • 6. Example  Fragment:  main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <fragment android:id="@+id/fragment1" android:name="com.example.fragmentexample.LeftFragment" android:layout_width="0dp" android:layout_weight="0.5" android:layout_height="match_parent" /> <fragment android:id="@+id/fragment2" android:name="com.example.fragmentexample.RightFragment" android:layout_width="0dp" android:layout_weight="0.5" android:layout_height="match_parent" /> </LinearLayout>
  • 7. Example  Fragment:  LeftFragment.java public class LeftFragment extends Fragment { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Button tv = new Button(getActivity()); tv.setText("left!"); return tv; } }
  • 8. Example  Fragment:  RightFragment.java public class RightFragment extends Fragment { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Button tv = new Button(getActivity()); tv.setText("right!"); return tv; } }
  • 9.
  • 10. Fragment  may  hold  XML  too!   public class RightFragment extends Fragment { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Let’s remove these // Button tv = new Button(getActivity()); // tv.setText("right!"); // return tv; // Creates Java object from the given XML file. View view = inflater.inflate(R.layout.right_fragment, // The xml file container, false); return view; } }
  • 11. FragmentManager •  FragmentManager  class  provides  methods   that  allow  you  to  add,  remove  and  replace   fragments  to  on  ac>vity  at  run>me.   •  Don’t  add  fragments  to  .xml,  but  perform   transac>on  in  Java   •  See:     –  https://developer.android.com/training/basics/ fragments/fragment-ui.html
  • 12. FragmentManager:     GeYng  reference  to  fragments   // Activity has getFragmentManager() – method! FragmentManager fragmentManager = getFragmentManager(); ChooseTitleFragment ctf = (ChooseTitleFragment) fragmentManager.findFragmentById(R.id.choose);
  • 13. Communica>on  Between  Fragments   •  Build  each  Fragment  UI  as  separate!   •  Do  Fragment  -­‐>  Fragment  communica>on   through  Ac>vity   •  Fragment  A  -­‐>  Ac8vity   – Use  your  own  interface,  ac>vity  can  be  whatever   •  Ac8vity  -­‐>  Fragment  B   – Use  FragmentManager  to  get  a  reference  to   Fragment  B  and  call  it’s  public  methods  
  • 14. public class ButtonFragment extends Fragment { // Helper interface for communicating with Activity public interface OnButtonClickedListener { public void buttonClicked(); } // Host Activity is here private OnButtonClickedListener callback; // When creating this fragment, host activity must be given and it must // implement OnButtonClickedListener interface. Method is called when fragment has // been associated with activity. The Activity is passed here! @Override public void onAttach(Activity activity) { super.onAttach(activity); callback = (OnButtonClickedListener) activity; } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Creates Java object from the given XML file. View view = inflater.inflate(R.layout.button_fragment, // The xml file container, false); Button sent = (Button) view.findViewById(R.id.button1); // When button is clicked, call activity's buttonClicked method sent.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { callback.buttonClicked(); } }); return view; } }
  • 15. Ac>vity   public class MainActivity extends Activity implements ButtonFragment.OnButtonClickedListener { @Override public void onCreate(Bundle b) { super.onCreate(b); // Holds ButtonFragment setContentView(R.layout.main); } // This is called when button is pressed in the fragment! @Override public void buttonClicked() { } }
  • 17. Use  layout/  directories   •  layout/main.xml   – One  dim  layout  (holds  Fragment  A)   •  layout-­‐land/main.xml   – Two  dim  layout  (holds  Fragment  A  +  B)   •  layout-­‐large/main.xml   – Two  dim  layout  (holds  Fragment  A  +  B)  
  • 18. public class MainActivity extends Activity implements ButtonFragment.OnButtonClickedListener { @Override public void onCreate(Bundle b) { super.onCreate(b); // Holds either two-dim or on-dim layout! hold either // 1) left-pane or // 2) left-pane and right-pane setContentView(R.layout.main); } // This is called when button is pressed in the fragment! @Override public void buttonClicked() { // Let's get a reference to the right fragment RightPaneFragment rightPaneFragment = (RightPaneFragment) getFragmentManager() .findFragmentById(R.id.right_fragment); // If it's not accessible, we are in one-dim layout if (rigthPaneFragment == null) { startNewActivity(); } else { updateRightPane(); } } private void startNewActivity() { Intent showContent = new Intent(this, RightActivityPane.class); // This activity holds RightPaneFragment startActivity(showContent); } private void updateRightPane(RightPaneFragment rightPaneFragment) { rightPaneFragment.doSomething(); } }