SlideShare a Scribd company logo
Mobile App Development
Lesson 5 - Spinners, Adapters & Fragment
Communication
Today’s Lesson
● More UI Components - Tonight Spinners
● string-array resources
● ArrayAdapter
● Fragment to Fragment comunication
Previous Lesson
● Fragments - We create them statically
● String resources
● Multiple Layouts, Multiple Devices = Multiple Layout
XML files (use pre-defined names)
● android:weight should be used with LinearLayout
Android UI - Next Steps
● So far we’ve seen Buttons and TextView components.
The next step is Spinners, Pickers & ListView. Spinners
this week.
● Spinners are what we commonly know elsewhere as
drop-down lists.
● A typical example would be a drop down list containing
a list of countries.
● Spinners can be populated statically or dynamically.
Spinner Population
● If we are putting a known/pre-defined & fixed list of
values into a Spinner (e.g. List of Countries) we can use a
String array. This is static population.
● As previously mentioned Strings in our app should be
defined as String resources (in res/values/strings.xml )
● We can define String arrays in this file as well as just
<string> using the <string-array> tag.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="selectcountry">Choose a country</string>
<string-array name="countryarray">
<item>Ireland</item>
<item>France</item>
<item>Spain</item>
<item>Poland</item>
</string-array>
</resources>
string-array resource
Using string-array
● To use the values in the string-array we just defined
we go back to our XML UI file of our Fragment or
Activity
● As before we can add a UI component by dragging and
dropping it on the UI designer or adding it directly in
the XML file.
● Either way the XML UI tag that results is <Spinner>
● We can link the <Spinner> directly to the string-array
resource via the XML.
Spinner & string-array
<Spinner
android:id="@+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="@array/country_array"
android:prompt="@string/selectcountry"
/>
● The link is made via the new XML Spinner property
android:entries
● NOTE : android:prompt only has an effect in dialog
mode (explained on next slide)
Getting value from Spinner
● By default we end up with a Spinner which looks like
this
1. This is the default type of
picker and is of type
“dropdown”
1. You can also display it as a
dialog by using the following
property in your Spinner XML
android:spinnerMode="dialog"
dialog Spinner mode
● We get slightly
different behaviour
from dialog mode.
● The title of the
dialog comes from
the android:prompt
property
Getting value from Spinner
Spinner sp1 = (Spinner)findViewById(R.id.spinner1);
String str = sp1.getSelectedItem().toString();
● It is worth mentioning at this stage that we can add an
array of anything behind a Spinner.
● This would be done programatically as opposed to
through XML for the strings we just saw.
● Presume we had an ArrayList<Person>. To get this into
our list we need an Adapter.
What is an Adapter ?
● For those who have done Swing UI, an Adapter in Android
is similar to the like of a TableModel in swing.
● It is a bridge or translator between the model (data) and
more complex UI components. It is part of the GUI.
● For Spinner the easiest option for displaying an ArrayList
of object is to use ArrayAdapter
● As in Swing objects which are not Strings will use
toString representation of the object for display.
Adding Objects to Spinner
Person p1 = new Person(“john”, 50);
Person p2 = new Person(“mary”, 60);
ArrayList<Person> peopleList = new ArrayList<Person>();
peopleList.add(p1);
peopleList.add(p2);
Spinner sp1 = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> spinnerArrayAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
peopleList);
sp1.setAdapter(spinnerArrayAdapter);
Fragment Communication
● As we have seen fragments are “self-contained
modular components” (which exist inside an Activity)
● What happens when a Fragment wants to send a
message elsewhere ? (To another Fragment ? To
another Activity ?)
● NB : All communication must be done through the
Fragment’s associated Activity.
Fragment communication
● The first step is to allow the Fragment to communicate
“up to” its Activity.
● To do this we define a simple Java interface which
defines what messages (i.e. method calls) the
Fragment can make.
● This interface is usally put inside the Java class of the
Fragment which wants to communicate.
● The content of the interface is entirely up to us.
The Scenario
MainActivity
TopFragment
BottomFragment
For messaging
between
Fragments
communication
MUST be done
through the
Activity
Fragment Communication
interface
public class TopFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_bottom, container,
false);
}
}
Presume we already have a basic fragment class
public interface SomethingHappenedInFragment
{
public void sendAMessage(String
message);
}
Put the
communication
interface
within the
Fragment class
Activity implements Fragment
interface
● After defining the interface the Activity which the
Fragment needs to communicate with must implement
that interface.
public class MainActivity
extends Activity implements TopFragment.SomethingHappenedInFragment
{
//The rest of the Activity will already be HERE(onCreate() etc)
//..and now the implementation of the SomethingHappenedInFragment
interface
public void sendAMessage(String message)
{
}
Message from
source fragment
arrives here
Delivering the
message
● Once the Activity receives the message it needs to find the
Fragment (or Fragments) to deliver the communication to (ie.
Call a method on.
public void sendAMessage(String message)
{
FragmentManager fMgr = getFragmentManager();
//Look up the destination fragment
BottomFragment bottomFrag =
(BottomFragment)fMgr.findFragmentById(R.id.fragment_bottom);
//Call a method on the destination fragment
bottomFrag.someMethodWhichWantsTheMessage(message);
}.
What’s Missing?
MainActivity
TopFragment
BottomFragment
public interface
SomethingHappenedInFragment {
public void sendMessage(String s);
}
implements
SomethingHappenedInFragment
public void sendMessage(String s)
{
}
TopFragment doesn’t have
a reference to
MainActivity ???
MainActivity can
find BottomFragment
by ID
The Final Step
● As part of the lifecycle of Activities and Fragments the
Activity “attaches itself” to its Fragments.
● Last week we saw the Fragment lifecycle method
onCreateView which MUST be implemented to get your
Fragment running.
● Before on onCreateView there is an earlier method in the
Fragment lifecycle called onAttach
● onAttach is called by the Activity which conveniently
passes a reference to itself. We store this reference.
The Code
public class TopFragment extends Fragment
{
private SomethingHappenedInFragment activity;
@Override
public void onAttach(Activity activity)
{
this.activity = (SomethingHappenedInFragment)activity
}
}
Remember : Our Activity
implements
SomethingHappenedInFragment
so it “is a”
SomethingHappenedInFragment

More Related Content

Viewers also liked

Cr 206 ag memoir introduction
Cr 206 ag memoir introductionCr 206 ag memoir introduction
Cr 206 ag memoir introduction
English Tribe
 
Android programming basics
Android programming basicsAndroid programming basics
Android programming basics
Egerton University
 
Lesson 4
Lesson 4Lesson 4
Lesson 4
CITSimon
 
Android 101 - Introduction to Android Development
Android 101 - Introduction to Android DevelopmentAndroid 101 - Introduction to Android Development
Android 101 - Introduction to Android Development
Andy Scherzinger
 
Android Fragment Pattern: Communication
Android Fragment Pattern: CommunicationAndroid Fragment Pattern: Communication
Android Fragment Pattern: Communication
zmontesd
 
Android App Development - 06 Fragments
Android App Development - 06 FragmentsAndroid App Development - 06 Fragments
Android App Development - 06 Fragments
Diego Grancini
 
Android - Working with Fragments
Android - Working with FragmentsAndroid - Working with Fragments
Android - Working with Fragments
Can Elmas
 
Screen orientations in android
Screen orientations in androidScreen orientations in android
Screen orientations in android
manjakannar
 
Android - Preventing common memory leaks
Android - Preventing common memory leaksAndroid - Preventing common memory leaks
Android - Preventing common memory leaks
Ali Muzaffar
 
Short Intro to Android Fragments
Short Intro to Android FragmentsShort Intro to Android Fragments
Short Intro to Android Fragments
Jussi Pohjolainen
 
Fragment
Fragment Fragment
Android Training (Storing & Shared Preferences)
Android Training (Storing & Shared Preferences)Android Training (Storing & Shared Preferences)
Android Training (Storing & Shared Preferences)
Khaled Anaqwa
 
Introduction to Android Fragments
Introduction to Android FragmentsIntroduction to Android Fragments
Introduction to Android Fragments
Sergi Martínez
 
Android memory fundamentals
Android memory fundamentalsAndroid memory fundamentals
Android memory fundamentals
Taras Leskiv
 
Fragmentation and types of fragmentation in Distributed Database
Fragmentation and types of fragmentation in Distributed DatabaseFragmentation and types of fragmentation in Distributed Database
Fragmentation and types of fragmentation in Distributed Database
Abhilasha Lahigude
 

Viewers also liked (15)

Cr 206 ag memoir introduction
Cr 206 ag memoir introductionCr 206 ag memoir introduction
Cr 206 ag memoir introduction
 
Android programming basics
Android programming basicsAndroid programming basics
Android programming basics
 
Lesson 4
Lesson 4Lesson 4
Lesson 4
 
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
 
Android App Development - 06 Fragments
Android App Development - 06 FragmentsAndroid App Development - 06 Fragments
Android App Development - 06 Fragments
 
Android - Working with Fragments
Android - Working with FragmentsAndroid - Working with Fragments
Android - Working with Fragments
 
Screen orientations in android
Screen orientations in androidScreen orientations in android
Screen orientations in android
 
Android - Preventing common memory leaks
Android - Preventing common memory leaksAndroid - Preventing common memory leaks
Android - Preventing common memory leaks
 
Short Intro to Android Fragments
Short Intro to Android FragmentsShort Intro to Android Fragments
Short Intro to Android Fragments
 
Fragment
Fragment Fragment
Fragment
 
Android Training (Storing & Shared Preferences)
Android Training (Storing & Shared Preferences)Android Training (Storing & Shared Preferences)
Android Training (Storing & Shared Preferences)
 
Introduction to Android Fragments
Introduction to Android FragmentsIntroduction to Android Fragments
Introduction to Android Fragments
 
Android memory fundamentals
Android memory fundamentalsAndroid memory fundamentals
Android memory fundamentals
 
Fragmentation and types of fragmentation in Distributed Database
Fragmentation and types of fragmentation in Distributed DatabaseFragmentation and types of fragmentation in Distributed Database
Fragmentation and types of fragmentation in Distributed Database
 

Similar to Spinners, Adapters & Fragment Communication

Lesson 3
Lesson 3Lesson 3
Lesson 3
CITSimon
 
MAD-Lec8 Spinner Adapater and Intents (1).ppt
MAD-Lec8 Spinner Adapater and Intents (1).pptMAD-Lec8 Spinner Adapater and Intents (1).ppt
MAD-Lec8 Spinner Adapater and Intents (1).ppt
AnsarAhmad57
 
Mobile Application Development class 002
Mobile Application Development class 002Mobile Application Development class 002
Mobile Application Development class 002
Dr. Mazin Mohamed alkathiri
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
prasnt1
 
Android training day 5
Android training day 5Android training day 5
Android training day 5
Vivek Bhusal
 
Android 3
Android 3Android 3
Android 3
Robert Cooper
 
Java
JavaJava
cbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptxcbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptx
tcsonline1222
 
Android
AndroidAndroid
Android
Pranav Ashok
 
"Android" mobilių programėlių kūrimo įvadas #2
"Android" mobilių programėlių kūrimo įvadas #2"Android" mobilių programėlių kūrimo įvadas #2
"Android" mobilių programėlių kūrimo įvadas #2
Tadas Jurelevičius
 
Bai giang-uml-11feb14
Bai giang-uml-11feb14Bai giang-uml-11feb14
.NET F# Events
.NET F# Events.NET F# Events
.NET F# Events
DrRajeshreeKhande
 
Introduction to Android Development
Introduction to Android DevelopmentIntroduction to Android Development
Introduction to Android Development
Aly Abdelkareem
 
Five android architecture
Five android architectureFive android architecture
Five android architecture
Tomislav Homan
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
Yekmer Simsek
 
Flutter tutorial for Beginner Step by Step
Flutter tutorial for Beginner Step by StepFlutter tutorial for Beginner Step by Step
Flutter tutorial for Beginner Step by Step
Chandramouli Biyyala
 
JSON Logger Baltimore Meetup
JSON Logger Baltimore MeetupJSON Logger Baltimore Meetup
JSON Logger Baltimore Meetup
ManjuKumara GH
 
How to create ui using droid draw
How to create ui using droid drawHow to create ui using droid draw
How to create ui using droid draw
info_zybotech
 
Classes and objects1
Classes and objects1Classes and objects1
Classes and objects1
Vineeta Garg
 
Android Development project
Android Development projectAndroid Development project
Android Development project
Minhaj Kazi
 

Similar to Spinners, Adapters & Fragment Communication (20)

Lesson 3
Lesson 3Lesson 3
Lesson 3
 
MAD-Lec8 Spinner Adapater and Intents (1).ppt
MAD-Lec8 Spinner Adapater and Intents (1).pptMAD-Lec8 Spinner Adapater and Intents (1).ppt
MAD-Lec8 Spinner Adapater and Intents (1).ppt
 
Mobile Application Development class 002
Mobile Application Development class 002Mobile Application Development class 002
Mobile Application Development class 002
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
 
Android training day 5
Android training day 5Android training day 5
Android training day 5
 
Android 3
Android 3Android 3
Android 3
 
Java
JavaJava
Java
 
cbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptxcbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptx
 
Android
AndroidAndroid
Android
 
"Android" mobilių programėlių kūrimo įvadas #2
"Android" mobilių programėlių kūrimo įvadas #2"Android" mobilių programėlių kūrimo įvadas #2
"Android" mobilių programėlių kūrimo įvadas #2
 
Bai giang-uml-11feb14
Bai giang-uml-11feb14Bai giang-uml-11feb14
Bai giang-uml-11feb14
 
.NET F# Events
.NET F# Events.NET F# Events
.NET F# Events
 
Introduction to Android Development
Introduction to Android DevelopmentIntroduction to Android Development
Introduction to Android Development
 
Five android architecture
Five android architectureFive android architecture
Five android architecture
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
 
Flutter tutorial for Beginner Step by Step
Flutter tutorial for Beginner Step by StepFlutter tutorial for Beginner Step by Step
Flutter tutorial for Beginner Step by Step
 
JSON Logger Baltimore Meetup
JSON Logger Baltimore MeetupJSON Logger Baltimore Meetup
JSON Logger Baltimore Meetup
 
How to create ui using droid draw
How to create ui using droid drawHow to create ui using droid draw
How to create ui using droid draw
 
Classes and objects1
Classes and objects1Classes and objects1
Classes and objects1
 
Android Development project
Android Development projectAndroid Development project
Android Development project
 

Recently uploaded

openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Neo4j
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
Grant Fritchey
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
What is Master Data Management by PiLog Group
What is Master Data Management by PiLog GroupWhat is Master Data Management by PiLog Group
What is Master Data Management by PiLog Group
aymanquadri279
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
Peter Muessig
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Julian Hyde
 
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise EditionWhy Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Envertis Software Solutions
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
Ayan Halder
 
DDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systemsDDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systems
Gerardo Pardo-Castellote
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptxLORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
lorraineandreiamcidl
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
Aftab Hussain
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
Remote DBA Services
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
Deuglo Infosystem Pvt Ltd
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
Hornet Dynamics
 

Recently uploaded (20)

openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
What is Master Data Management by PiLog Group
What is Master Data Management by PiLog GroupWhat is Master Data Management by PiLog Group
What is Master Data Management by PiLog Group
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
 
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise EditionWhy Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
 
DDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systemsDDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systems
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptxLORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
 

Spinners, Adapters & Fragment Communication

  • 1. Mobile App Development Lesson 5 - Spinners, Adapters & Fragment Communication
  • 2. Today’s Lesson ● More UI Components - Tonight Spinners ● string-array resources ● ArrayAdapter ● Fragment to Fragment comunication
  • 3. Previous Lesson ● Fragments - We create them statically ● String resources ● Multiple Layouts, Multiple Devices = Multiple Layout XML files (use pre-defined names) ● android:weight should be used with LinearLayout
  • 4. Android UI - Next Steps ● So far we’ve seen Buttons and TextView components. The next step is Spinners, Pickers & ListView. Spinners this week. ● Spinners are what we commonly know elsewhere as drop-down lists. ● A typical example would be a drop down list containing a list of countries. ● Spinners can be populated statically or dynamically.
  • 5. Spinner Population ● If we are putting a known/pre-defined & fixed list of values into a Spinner (e.g. List of Countries) we can use a String array. This is static population. ● As previously mentioned Strings in our app should be defined as String resources (in res/values/strings.xml ) ● We can define String arrays in this file as well as just <string> using the <string-array> tag.
  • 6. <?xml version="1.0" encoding="utf-8"?> <resources> <string name="selectcountry">Choose a country</string> <string-array name="countryarray"> <item>Ireland</item> <item>France</item> <item>Spain</item> <item>Poland</item> </string-array> </resources> string-array resource
  • 7. Using string-array ● To use the values in the string-array we just defined we go back to our XML UI file of our Fragment or Activity ● As before we can add a UI component by dragging and dropping it on the UI designer or adding it directly in the XML file. ● Either way the XML UI tag that results is <Spinner> ● We can link the <Spinner> directly to the string-array resource via the XML.
  • 8. Spinner & string-array <Spinner android:id="@+id/spinner1" android:layout_width="match_parent" android:layout_height="wrap_content" android:entries="@array/country_array" android:prompt="@string/selectcountry" /> ● The link is made via the new XML Spinner property android:entries ● NOTE : android:prompt only has an effect in dialog mode (explained on next slide)
  • 9. Getting value from Spinner ● By default we end up with a Spinner which looks like this 1. This is the default type of picker and is of type “dropdown” 1. You can also display it as a dialog by using the following property in your Spinner XML android:spinnerMode="dialog"
  • 10. dialog Spinner mode ● We get slightly different behaviour from dialog mode. ● The title of the dialog comes from the android:prompt property
  • 11. Getting value from Spinner Spinner sp1 = (Spinner)findViewById(R.id.spinner1); String str = sp1.getSelectedItem().toString(); ● It is worth mentioning at this stage that we can add an array of anything behind a Spinner. ● This would be done programatically as opposed to through XML for the strings we just saw. ● Presume we had an ArrayList<Person>. To get this into our list we need an Adapter.
  • 12. What is an Adapter ? ● For those who have done Swing UI, an Adapter in Android is similar to the like of a TableModel in swing. ● It is a bridge or translator between the model (data) and more complex UI components. It is part of the GUI. ● For Spinner the easiest option for displaying an ArrayList of object is to use ArrayAdapter ● As in Swing objects which are not Strings will use toString representation of the object for display.
  • 13. Adding Objects to Spinner Person p1 = new Person(“john”, 50); Person p2 = new Person(“mary”, 60); ArrayList<Person> peopleList = new ArrayList<Person>(); peopleList.add(p1); peopleList.add(p2); Spinner sp1 = (Spinner)findViewById(R.id.spinner1); ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, peopleList); sp1.setAdapter(spinnerArrayAdapter);
  • 14. Fragment Communication ● As we have seen fragments are “self-contained modular components” (which exist inside an Activity) ● What happens when a Fragment wants to send a message elsewhere ? (To another Fragment ? To another Activity ?) ● NB : All communication must be done through the Fragment’s associated Activity.
  • 15. Fragment communication ● The first step is to allow the Fragment to communicate “up to” its Activity. ● To do this we define a simple Java interface which defines what messages (i.e. method calls) the Fragment can make. ● This interface is usally put inside the Java class of the Fragment which wants to communicate. ● The content of the interface is entirely up to us.
  • 17. Fragment Communication interface public class TopFragment extends Fragment { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_bottom, container, false); } } Presume we already have a basic fragment class public interface SomethingHappenedInFragment { public void sendAMessage(String message); } Put the communication interface within the Fragment class
  • 18. Activity implements Fragment interface ● After defining the interface the Activity which the Fragment needs to communicate with must implement that interface. public class MainActivity extends Activity implements TopFragment.SomethingHappenedInFragment { //The rest of the Activity will already be HERE(onCreate() etc) //..and now the implementation of the SomethingHappenedInFragment interface public void sendAMessage(String message) { } Message from source fragment arrives here
  • 19. Delivering the message ● Once the Activity receives the message it needs to find the Fragment (or Fragments) to deliver the communication to (ie. Call a method on. public void sendAMessage(String message) { FragmentManager fMgr = getFragmentManager(); //Look up the destination fragment BottomFragment bottomFrag = (BottomFragment)fMgr.findFragmentById(R.id.fragment_bottom); //Call a method on the destination fragment bottomFrag.someMethodWhichWantsTheMessage(message); }.
  • 20. What’s Missing? MainActivity TopFragment BottomFragment public interface SomethingHappenedInFragment { public void sendMessage(String s); } implements SomethingHappenedInFragment public void sendMessage(String s) { } TopFragment doesn’t have a reference to MainActivity ??? MainActivity can find BottomFragment by ID
  • 21. The Final Step ● As part of the lifecycle of Activities and Fragments the Activity “attaches itself” to its Fragments. ● Last week we saw the Fragment lifecycle method onCreateView which MUST be implemented to get your Fragment running. ● Before on onCreateView there is an earlier method in the Fragment lifecycle called onAttach ● onAttach is called by the Activity which conveniently passes a reference to itself. We store this reference.
  • 22. The Code public class TopFragment extends Fragment { private SomethingHappenedInFragment activity; @Override public void onAttach(Activity activity) { this.activity = (SomethingHappenedInFragment)activity } } Remember : Our Activity implements SomethingHappenedInFragment so it “is a” SomethingHappenedInFragment