SlideShare ist ein Scribd-Unternehmen logo
1 von 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();
}
}

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Andere mochten auch

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
 

Andere mochten auch (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
 

Ähnlich wie Build Dynamic UIs with 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
 

Ähnlich wie Build Dynamic UIs with 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
 

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
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
 

Kürzlich hochgeladen (20)

Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
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
 

Build Dynamic UIs with 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(); } }