SlideShare uma empresa Scribd logo
1 de 22
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

Mais conteúdo relacionado

Mais procurados

Something About Dynamic Linking
Something About Dynamic LinkingSomething About Dynamic Linking
Something About Dynamic LinkingWang Hsiangkai
 
Redhat Open Day - Integracion JBoss Fuse A-MQ
Redhat Open Day - Integracion JBoss Fuse A-MQRedhat Open Day - Integracion JBoss Fuse A-MQ
Redhat Open Day - Integracion JBoss Fuse A-MQAdrian Gigante
 
빠른 모바일 인증 구현을 위한 Amazon Cognito 서비스 소개 :: 윤석찬 - AWS Monthly Webinar
빠른 모바일 인증 구현을 위한 Amazon Cognito 서비스 소개 :: 윤석찬 - AWS Monthly Webinar빠른 모바일 인증 구현을 위한 Amazon Cognito 서비스 소개 :: 윤석찬 - AWS Monthly Webinar
빠른 모바일 인증 구현을 위한 Amazon Cognito 서비스 소개 :: 윤석찬 - AWS Monthly WebinarAmazon Web Services Korea
 
Mastering Async/Await in JavaScript
Mastering Async/Await in JavaScriptMastering Async/Await in JavaScript
Mastering Async/Await in JavaScriptValeri Karpov
 
Angular js routing options
Angular js routing optionsAngular js routing options
Angular js routing optionsNir Kaufman
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummiesLuis Goldster
 
Implementing a JavaScript Engine
Implementing a JavaScript EngineImplementing a JavaScript Engine
Implementing a JavaScript EngineKris Mok
 
Formation jpa-hibernate-spring-data
Formation jpa-hibernate-spring-dataFormation jpa-hibernate-spring-data
Formation jpa-hibernate-spring-dataLhouceine OUHAMZA
 
WebAssembly Fundamentals
WebAssembly FundamentalsWebAssembly Fundamentals
WebAssembly FundamentalsKnoldus Inc.
 
Cucumber - Curso de Automatización de Pruebas
Cucumber - Curso de Automatización de PruebasCucumber - Curso de Automatización de Pruebas
Cucumber - Curso de Automatización de PruebasTestingBaires
 
아해2019 SpringAOP 문겸
아해2019 SpringAOP 문겸아해2019 SpringAOP 문겸
아해2019 SpringAOP 문겸MoonGyeom1
 

Mais procurados (20)

Unit iv
Unit ivUnit iv
Unit iv
 
Mediator pattern
Mediator patternMediator pattern
Mediator pattern
 
Something About Dynamic Linking
Something About Dynamic LinkingSomething About Dynamic Linking
Something About Dynamic Linking
 
Redhat Open Day - Integracion JBoss Fuse A-MQ
Redhat Open Day - Integracion JBoss Fuse A-MQRedhat Open Day - Integracion JBoss Fuse A-MQ
Redhat Open Day - Integracion JBoss Fuse A-MQ
 
Broadcast Receiver
Broadcast ReceiverBroadcast Receiver
Broadcast Receiver
 
빠른 모바일 인증 구현을 위한 Amazon Cognito 서비스 소개 :: 윤석찬 - AWS Monthly Webinar
빠른 모바일 인증 구현을 위한 Amazon Cognito 서비스 소개 :: 윤석찬 - AWS Monthly Webinar빠른 모바일 인증 구현을 위한 Amazon Cognito 서비스 소개 :: 윤석찬 - AWS Monthly Webinar
빠른 모바일 인증 구현을 위한 Amazon Cognito 서비스 소개 :: 윤석찬 - AWS Monthly Webinar
 
Solid principles
Solid principlesSolid principles
Solid principles
 
Mastering Async/Await in JavaScript
Mastering Async/Await in JavaScriptMastering Async/Await in JavaScript
Mastering Async/Await in JavaScript
 
DDD Introduction
DDD IntroductionDDD Introduction
DDD Introduction
 
Enterprise Service Bus
Enterprise Service BusEnterprise Service Bus
Enterprise Service Bus
 
Angular js routing options
Angular js routing optionsAngular js routing options
Angular js routing options
 
Android Networking
Android NetworkingAndroid Networking
Android Networking
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
 
05 intent
05 intent05 intent
05 intent
 
Dart ppt
Dart pptDart ppt
Dart ppt
 
Implementing a JavaScript Engine
Implementing a JavaScript EngineImplementing a JavaScript Engine
Implementing a JavaScript Engine
 
Formation jpa-hibernate-spring-data
Formation jpa-hibernate-spring-dataFormation jpa-hibernate-spring-data
Formation jpa-hibernate-spring-data
 
WebAssembly Fundamentals
WebAssembly FundamentalsWebAssembly Fundamentals
WebAssembly Fundamentals
 
Cucumber - Curso de Automatización de Pruebas
Cucumber - Curso de Automatización de PruebasCucumber - Curso de Automatización de Pruebas
Cucumber - Curso de Automatización de Pruebas
 
아해2019 SpringAOP 문겸
아해2019 SpringAOP 문겸아해2019 SpringAOP 문겸
아해2019 SpringAOP 문겸
 

Destaque

Cr 206 ag memoir introduction
Cr 206 ag memoir introductionCr 206 ag memoir introduction
Cr 206 ag memoir introductionEnglish Tribe
 
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
 
Android App Development - 06 Fragments
Android App Development - 06 FragmentsAndroid App Development - 06 Fragments
Android App Development - 06 FragmentsDiego Grancini
 
Android - Working with Fragments
Android - Working with FragmentsAndroid - Working with Fragments
Android - Working with FragmentsCan Elmas
 
Screen orientations in android
Screen orientations in androidScreen orientations in android
Screen orientations in androidmanjakannar
 
Android - Preventing common memory leaks
Android - Preventing common memory leaksAndroid - Preventing common memory leaks
Android - Preventing common memory leaksAli Muzaffar
 
Short Intro to Android Fragments
Short Intro to Android FragmentsShort Intro to Android Fragments
Short Intro to Android FragmentsJussi Pohjolainen
 
Android Training (Storing & Shared Preferences)
Android Training (Storing & Shared Preferences)Android Training (Storing & Shared Preferences)
Android Training (Storing & Shared Preferences)Khaled Anaqwa
 
Introduction to Android Fragments
Introduction to Android FragmentsIntroduction to Android Fragments
Introduction to Android FragmentsSergi Martínez
 
Android memory fundamentals
Android memory fundamentalsAndroid memory fundamentals
Android memory fundamentalsTaras 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 DatabaseAbhilasha Lahigude
 

Destaque (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
 

Semelhante a Spinners, Adapters & Fragment Communication

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).pptAnsarAhmad57
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdfprasnt1
 
Android training day 5
Android training day 5Android training day 5
Android training day 5Vivek Bhusal
 
"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 #2Tadas Jurelevičius
 
Introduction to Android Development
Introduction to Android DevelopmentIntroduction to Android Development
Introduction to Android DevelopmentAly Abdelkareem
 
Five android architecture
Five android architectureFive android architecture
Five android architectureTomislav Homan
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best PracticesYekmer 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 StepChandramouli Biyyala
 
JSON Logger Baltimore Meetup
JSON Logger Baltimore MeetupJSON Logger Baltimore Meetup
JSON Logger Baltimore MeetupManjuKumara 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 drawinfo_zybotech
 
Classes and objects1
Classes and objects1Classes and objects1
Classes and objects1Vineeta Garg
 
Android Development project
Android Development projectAndroid Development project
Android Development projectMinhaj Kazi
 
Tour de Jackson: Forgotten Features of Jackson JSON processor
Tour de Jackson: Forgotten Features of Jackson JSON processorTour de Jackson: Forgotten Features of Jackson JSON processor
Tour de Jackson: Forgotten Features of Jackson JSON processorTatu Saloranta
 

Semelhante a 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
 
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
 
Tour de Jackson: Forgotten Features of Jackson JSON processor
Tour de Jackson: Forgotten Features of Jackson JSON processorTour de Jackson: Forgotten Features of Jackson JSON processor
Tour de Jackson: Forgotten Features of Jackson JSON processor
 

Último

Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 

Último (20)

Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 

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