SlideShare a Scribd company logo
ListViews, GridViews, Adapters,
Dialogs and Toasts
ListViews, GridViews, Adapters, Dialogs and Toasts
A ListView or a GridView shows data in an array, a Collection or a
Cursor resulting from a DB query.
Contrary to what happens with the other View, the data entry is
done at runtime using an Adapter that tells the system how to
insert the data specifying the graphical interface of each element.
To simplify this management it provides lists of specialized
classes like ListActivity and ListFragment that add methods to
handle the ListView without recovering its reference from the
layout.
ListViews and GridViews
The main class that manages the View that make a list or a grid is
BaseAdapter.
The platform provides specializations of this class to simplify the
creation of the view that compose a list or grid, but restrict them
customization.
● ArrayAdapter<T>
● SimpleAdapter
● CursorAdapter
● SimpleCursorAdapter
Adapters
ListViews, GridViews, Adapters, Dialogs and Toasts
public class ExampleAdapter extends BaseAdapter {
@Override
public int getCount() {
return 0;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return null;
}
}
BaseAdapter
ListViews, GridViews, Adapters, Dialogs and Toasts
public class ExampleAdapter extends BaseAdapter {
private List<String> titles;
@Override
public int getCount() {
if (titles != null)
return titles.size();
return 0;
}
@Override
public String getItem(int position) {
return titles.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return convertView;
}
}
BaseAdapter
ListViews, GridViews, Adapters, Dialogs and Toasts
public class ExampleAdapter extends BaseAdapter {
private List<String> titles;
private LayoutInflater inflater;
public ExampleAdapter(Context context) {
inflater = LayoutInflater.from(context);
}
...
@Override
public View getView(int position, View convertView, ViewGroup parent) {
String title = getItem(position);
convertView = inflater.inflate(R.layout.example_item, null);
TextView titleView = (TextView) convertView
.findViewById(R.id.example_title);
titleView.setText(title);
return convertView;
}
}
BaseAdapter
ListViews, GridViews, Adapters, Dialogs and Toasts
All the times that you have to make a visible element of the list, a
call is made to Adapter.getView () on the Main Thread because
only this can change the graphical interface.
Whether to complex View or simple View, this may affect the
fluidity of the ListView and in the worst cases the entire
application. The cause of this is the call to View.findViewById ()
that search for reference of the instance of a View.
In most cases the View loaded for each element of the list is the
same, then all subsequent calls to the first to retrieve the View
can be eliminated by maintaining a reference to all of the Layout
View.
To do this you must use the View Holder Pattern.
BaseAdapter - Limits
ListViews, GridViews, Adapters, Dialogs and Toasts
A ViewHolder object stores a reference of each of the Layout
View in order to reuse it for all elements.
public class ExampleAdapter extends BaseAdapter {
private List<String> titles;
private LayoutInflater inflater;
...
@Override
public View getView(int position, View convertView, ViewGroup parent) {
String title = getItem(position);
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.example_item, null);
holder = new ViewHolder();
holder.titleView = (TextView) convertView
.findViewById(R.id.example_title);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.titleView.setText(title);
return convertView;
}
static class ViewHolder {
TextView titleView;
}
}
View Holder Pattern
ListViews, GridViews, Adapters, Dialogs and Toasts
ArrayAdapter is a concrete class that allows the insertion of a
simple list in a ListView.
ArrayAdapter<String> itemsAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
By default, the text entered in the one TextView in the list is the
string returned by toString().
ArrayAdapter<T>
ListViews, GridViews, Adapters, Dialogs and Toasts
SimpleAdapter (as the ArrayAdapter) is a concrete class that
allows the insertion of a simple list in a ListView, but allows a
greater level of customization.
List<Map<String, String>> data = new ArrayList<Map<String, String>>();
data.add(new HashMap<String, String>() {
{
put("description", "10100");
put("title", "Torino");
}
});
...
ListAdapter adapter = new SimpleAdapter(this, data,
android.R.layout.simple_list_item_2, new String[] { "title",
"description" }, new int[] { android.R.id.text1,
android.R.id.text2 });
SimpleAdapter
ListViews, GridViews, Adapters, Dialogs and Toasts
CursorAdapter is an abstract class that simplifies the
management of data from a DataBase to show them in a
ListView.
It is not necessary to implement the ViewHolderPattern, because
the class manages the reuse of View.
public class ExampleCursorAdapter extends CursorAdapter {
private LayoutInflater inflater;
public ExampleCursorAdapter(Context context, Cursor c, boolean autoRequery) {
super(context, c, autoRequery);
inflater = LayoutInflater.from(context);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView titleText = (TextView) view.findViewById(R.id.example_title);
String title = cursor.getString(cursor.getColumnIndex("title"));
titleText.setText(title);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return inflater.inflate(R.layout.example_item, null);
}
}
CursorAdapter
ListViews, GridViews, Adapters, Dialogs and Toasts
Once you have created the adapter, it should be assigned to the
ListView or GridView with the method:
listView.setAdapter(adapter);
After you've assigned all'AdapterView, you no longer need to
instantiate a new one: if and when the data passed to the adapter
undergo a change, it is necessary and sufficient to invoke the
method Adapter.notifyDataSetChanged () to apply your changes
and force the update of the list.
adapter.notifyDataSetChanged();
N.B.: If you change the data, but the method
Adapter.notifyDataSetChanged() is not called, the system will
throw an IllegalStateException.
Data management
ListViews, GridViews, Adapters, Dialogs and Toasts
A Dialog is a small window that asks the user to make a selection
or enter additional information.
Dialog
ListViews, GridViews, Adapters, Dialogs and Toasts
The Dialog class is the base for the management of this type of
objects, but the platform makes available to the specialization for
certain purposes:
● AlertDialog: Dialog that shows a title, a message and up to 3
Button
● DatePickerDialog: Dialog with default layout that allows the
user to select a date
● TimePickerDialog: Dialog with default layout that allows the
user to select a time
● ProgressDialog: Dialog with title, message and a
ProgressBar to notify the user waiting for an operation of long
duration. Use of this Dialog is not recommended because it
prevents the user from interacting with the application.
Dialog
ListViews, GridViews, Adapters, Dialogs and Toasts
To create a Dialog you can create an instance and define the
graphical interface:
Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.example_dialog);
TextView title = (TextView) dialog.findViewById(R.id.example_title);
Button close = dialog.findViewById(R.id.example_close);
close.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
dialog.cancel();
}
});
title.setText("Title");
dialog.show();
Dialog
ListViews, GridViews, Adapters, Dialogs and Toasts
With the introduction of the Fragment, it was added the possibility
of extending DialogFragment to create Dialog. This allows you to
add it to an Activity or show it like a Dialog.
The DialogFragment class has pne more method than the
Fragment: it's used to create the instance of Dialog in which to
display the Fragment to the invocation of the method
DialogFragment.show()
public class ExampleDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.example_dialog_fragment);
return dialog;
}
}
DialogFragment
ListViews, GridViews, Adapters, Dialogs and Toasts
An AlertDialog is composed by 3 main components:
● Title: optional
● Content: a message, a list or a custom layout
● Actions: up to 3 buttons
AlertDialog
ListViews, GridViews, Adapters, Dialogs and Toasts
In order to create an AlertDialog, use an AlertDialog.Builder:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_message).setTitle(
R.string.dialog_title);
// Add the buttons
builder.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
}
});
builder.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
AlertDialog dialog = builder.create();
AlertDialog - Button
ListViews, GridViews, Adapters, Dialogs and Toasts
In order to create an AlertDialog, use an AlertDialog.Builder:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.pick_color);
builder.setItems(R.array.colors_array,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
}
});
AlertDialog dialog = builder.create();
AlertDialog - List
ListViews, GridViews, Adapters, Dialogs and Toasts
In order to create an AlertDialog, use an AlertDialog.Builder:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
mSelectedItems = new ArrayList<Integer>();
builder.setTitle(R.string.pick_color).setMultiChoiceItems(
R.array.toppings, null,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the
// selected items
mSelectedItems.add(which);
} else if (mSelectedItems.contains(which)) {
// Else, if the item is already in the array,
// remove it
mSelectedItems.remove(Integer.valueOf(which));
}
}
});
AlertDialog dialog = builder.create();
AlertDialog - MultiChoiceList
ListViews, GridViews, Adapters, Dialogs and Toasts
In order to create an AlertDialog, use an AlertDialog.Builder:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(inflater.inflate(R.layout.dialog_signin, null))
// Add action buttons
.setPositiveButton(R.string.signin,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,int id){
// sign in the user ...
}
})
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id){
LoginDialogFragment.this.getDialog().cancel();
}
});
AlertDialog dialog = builder.create();
AlertDialog – Custom Layout
ListViews, GridViews, Adapters, Dialogs and Toasts
If you do not want to use the Dialog API to show windows, you
can assign a Dialog style to the Activity declaring it in the Manifest
file:
<activity
android:name="com.example.test.MainActivity"
android:theme="@android:style/Theme.Holo.Dialog" >
</activity>
Activity as a Dialog
ListViews, GridViews, Adapters, Dialogs and Toasts
A Toast shows the user a message for a short period of time
without interaction.
Toast
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
ListViews, GridViews, Adapters, Dialogs and Toasts

More Related Content

What's hot

List adapter with multiple objects
List adapter with multiple objectsList adapter with multiple objects
List adapter with multiple objects
baabtra.com - No. 1 supplier of quality freshers
 
Android App Development - 04 Views and layouts
Android App Development - 04 Views and layoutsAndroid App Development - 04 Views and layouts
Android App Development - 04 Views and layouts
Diego Grancini
 
AdRotator and AdRepeater Control in Asp.Net for Msc CS
AdRotator and AdRepeater Control in Asp.Net for Msc CSAdRotator and AdRepeater Control in Asp.Net for Msc CS
AdRotator and AdRepeater Control in Asp.Net for Msc CS
Thanveen
 
Report cs3 pillos
Report cs3 pillosReport cs3 pillos
Report cs3 pillos
paul gonzaga
 
Oracle Index
Oracle IndexOracle Index
Oracle Index
Madhavendra Dutt
 
MS SQL SERVER: Programming sql server data mining
MS SQL SERVER: Programming sql server data miningMS SQL SERVER: Programming sql server data mining
MS SQL SERVER: Programming sql server data mining
DataminingTools Inc
 
List Views
List ViewsList Views
List Views
Ahsanul Karim
 
ASP.net Image Slideshow
ASP.net Image SlideshowASP.net Image Slideshow
ASP.net Image Slideshow
Hock Leng PUAH
 
Android L02 - Activities and Adapters
Android L02 - Activities and AdaptersAndroid L02 - Activities and Adapters
Android L02 - Activities and Adapters
Mohammad Shaker
 
Day 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViewsDay 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViews
Ahsanul Karim
 
Jaspersoft Studio Quick Start Guide
Jaspersoft Studio Quick Start GuideJaspersoft Studio Quick Start Guide
Jaspersoft Studio Quick Start Guide
Jeff Rix
 
Chapter 18
Chapter 18Chapter 18
Chapter 18
Graham Royce
 
SAP BO Web Intelligence Basics
SAP BO Web Intelligence BasicsSAP BO Web Intelligence Basics
SAP BO Web Intelligence Basics
Kiran Joy
 
Automotive industry ppt
Automotive industry pptAutomotive industry ppt
Automotive industry ppt
sudharsanpremkumar1
 
2310 b xc
2310 b xc2310 b xc
2310 b xc
Krazy Koder
 
C# Collection classes
C# Collection classesC# Collection classes
C# Collection classes
MohitKumar1985
 
Dev308
Dev308Dev308
Dev308
guest2130e
 
Java Generics wildcards
Java Generics wildcardsJava Generics wildcards
Java Generics wildcards
Kohei Nozaki
 
Creating EPiServer Usage Reports
Creating EPiServer Usage ReportsCreating EPiServer Usage Reports
Creating EPiServer Usage Reports
Paul Graham
 

What's hot (19)

List adapter with multiple objects
List adapter with multiple objectsList adapter with multiple objects
List adapter with multiple objects
 
Android App Development - 04 Views and layouts
Android App Development - 04 Views and layoutsAndroid App Development - 04 Views and layouts
Android App Development - 04 Views and layouts
 
AdRotator and AdRepeater Control in Asp.Net for Msc CS
AdRotator and AdRepeater Control in Asp.Net for Msc CSAdRotator and AdRepeater Control in Asp.Net for Msc CS
AdRotator and AdRepeater Control in Asp.Net for Msc CS
 
Report cs3 pillos
Report cs3 pillosReport cs3 pillos
Report cs3 pillos
 
Oracle Index
Oracle IndexOracle Index
Oracle Index
 
MS SQL SERVER: Programming sql server data mining
MS SQL SERVER: Programming sql server data miningMS SQL SERVER: Programming sql server data mining
MS SQL SERVER: Programming sql server data mining
 
List Views
List ViewsList Views
List Views
 
ASP.net Image Slideshow
ASP.net Image SlideshowASP.net Image Slideshow
ASP.net Image Slideshow
 
Android L02 - Activities and Adapters
Android L02 - Activities and AdaptersAndroid L02 - Activities and Adapters
Android L02 - Activities and Adapters
 
Day 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViewsDay 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViews
 
Jaspersoft Studio Quick Start Guide
Jaspersoft Studio Quick Start GuideJaspersoft Studio Quick Start Guide
Jaspersoft Studio Quick Start Guide
 
Chapter 18
Chapter 18Chapter 18
Chapter 18
 
SAP BO Web Intelligence Basics
SAP BO Web Intelligence BasicsSAP BO Web Intelligence Basics
SAP BO Web Intelligence Basics
 
Automotive industry ppt
Automotive industry pptAutomotive industry ppt
Automotive industry ppt
 
2310 b xc
2310 b xc2310 b xc
2310 b xc
 
C# Collection classes
C# Collection classesC# Collection classes
C# Collection classes
 
Dev308
Dev308Dev308
Dev308
 
Java Generics wildcards
Java Generics wildcardsJava Generics wildcards
Java Generics wildcards
 
Creating EPiServer Usage Reports
Creating EPiServer Usage ReportsCreating EPiServer Usage Reports
Creating EPiServer Usage Reports
 

Similar to Android App Development - 11 Lists, grids, adapters, dialogs and toasts

Disconnected Architecture and Crystal report in VB.NET
Disconnected Architecture and Crystal report in VB.NETDisconnected Architecture and Crystal report in VB.NET
Disconnected Architecture and Crystal report in VB.NET
Everywhere
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And Representation
Randy Connolly
 
Session 2- day 3
Session 2- day 3Session 2- day 3
Session 2- day 3
Vivek Bhusal
 
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
honey725342
 
How to become an Android dev starting from iOS (and vice versa)
How to become an Android dev starting from iOS (and vice versa)How to become an Android dev starting from iOS (and vice versa)
How to become an Android dev starting from iOS (and vice versa)
Giuseppe Filograno
 
Ado.net with asp.net
Ado.net with asp.netAdo.net with asp.net
Ado.net with asp.net
Sireesh K
 
Binding radgridview into reportviewer
Binding radgridview into reportviewerBinding radgridview into reportviewer
Binding radgridview into reportviewer
Junifar hidayat
 
Procedures functions structures in VB.Net
Procedures  functions  structures in VB.NetProcedures  functions  structures in VB.Net
Procedures functions structures in VB.Net
tjunicornfx
 
Reactive clean architecture
Reactive clean architectureReactive clean architecture
Reactive clean architecture
Viktor Nyblom
 
Android tutorials8 todo_list
Android tutorials8 todo_listAndroid tutorials8 todo_list
Android tutorials8 todo_list
Vlad Kolesnyk
 
Custom UI Components at Android Only 2011
Custom UI Components at Android Only 2011Custom UI Components at Android Only 2011
Custom UI Components at Android Only 2011
Johan Nilsson
 
Murach: How to transfer data from controllers
Murach: How to transfer data from controllersMurach: How to transfer data from controllers
Murach: How to transfer data from controllers
MahmoudOHassouna
 
GRID VIEW PPT
GRID VIEW PPTGRID VIEW PPT
2310 b 09
2310 b 092310 b 09
2310 b 09
Krazy Koder
 
Part3 Explain the Explain Plan
Part3 Explain the Explain PlanPart3 Explain the Explain Plan
Part3 Explain the Explain Plan
Maria Colgan
 
Breaking down data silos with the open data protocol
Breaking down data silos with the open data protocolBreaking down data silos with the open data protocol
Breaking down data silos with the open data protocol
Woodruff Solutions LLC
 
Android ListView and Custom ListView
Android ListView and Custom ListView Android ListView and Custom ListView
Android ListView and Custom ListView
Sourabh Sahu
 
Stata cheat sheet: data processing
Stata cheat sheet: data processingStata cheat sheet: data processing
Stata cheat sheet: data processing
Tim Essam
 
Spring data ii
Spring data iiSpring data ii
Spring data ii
명철 강
 
data controls in asp.net
data controls in asp.netdata controls in asp.net
data controls in asp.net
subakrish
 

Similar to Android App Development - 11 Lists, grids, adapters, dialogs and toasts (20)

Disconnected Architecture and Crystal report in VB.NET
Disconnected Architecture and Crystal report in VB.NETDisconnected Architecture and Crystal report in VB.NET
Disconnected Architecture and Crystal report in VB.NET
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And Representation
 
Session 2- day 3
Session 2- day 3Session 2- day 3
Session 2- day 3
 
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
 
How to become an Android dev starting from iOS (and vice versa)
How to become an Android dev starting from iOS (and vice versa)How to become an Android dev starting from iOS (and vice versa)
How to become an Android dev starting from iOS (and vice versa)
 
Ado.net with asp.net
Ado.net with asp.netAdo.net with asp.net
Ado.net with asp.net
 
Binding radgridview into reportviewer
Binding radgridview into reportviewerBinding radgridview into reportviewer
Binding radgridview into reportviewer
 
Procedures functions structures in VB.Net
Procedures  functions  structures in VB.NetProcedures  functions  structures in VB.Net
Procedures functions structures in VB.Net
 
Reactive clean architecture
Reactive clean architectureReactive clean architecture
Reactive clean architecture
 
Android tutorials8 todo_list
Android tutorials8 todo_listAndroid tutorials8 todo_list
Android tutorials8 todo_list
 
Custom UI Components at Android Only 2011
Custom UI Components at Android Only 2011Custom UI Components at Android Only 2011
Custom UI Components at Android Only 2011
 
Murach: How to transfer data from controllers
Murach: How to transfer data from controllersMurach: How to transfer data from controllers
Murach: How to transfer data from controllers
 
GRID VIEW PPT
GRID VIEW PPTGRID VIEW PPT
GRID VIEW PPT
 
2310 b 09
2310 b 092310 b 09
2310 b 09
 
Part3 Explain the Explain Plan
Part3 Explain the Explain PlanPart3 Explain the Explain Plan
Part3 Explain the Explain Plan
 
Breaking down data silos with the open data protocol
Breaking down data silos with the open data protocolBreaking down data silos with the open data protocol
Breaking down data silos with the open data protocol
 
Android ListView and Custom ListView
Android ListView and Custom ListView Android ListView and Custom ListView
Android ListView and Custom ListView
 
Stata cheat sheet: data processing
Stata cheat sheet: data processingStata cheat sheet: data processing
Stata cheat sheet: data processing
 
Spring data ii
Spring data iiSpring data ii
Spring data ii
 
data controls in asp.net
data controls in asp.netdata controls in asp.net
data controls in asp.net
 

More from Diego Grancini

Android App Development - 14 location, media and notifications
Android App Development - 14 location, media and notificationsAndroid App Development - 14 location, media and notifications
Android App Development - 14 location, media and notifications
Diego Grancini
 
Android App Development - 13 Broadcast receivers and app widgets
Android App Development - 13 Broadcast receivers and app widgetsAndroid App Development - 13 Broadcast receivers and app widgets
Android App Development - 13 Broadcast receivers and app widgets
Diego Grancini
 
Android App Development - 12 animations
Android App Development - 12 animationsAndroid App Development - 12 animations
Android App Development - 12 animations
Diego Grancini
 
Android App Development - 10 Content providers
Android App Development - 10 Content providersAndroid App Development - 10 Content providers
Android App Development - 10 Content providers
Diego Grancini
 
Android App Development - 09 Storage
Android App Development - 09 StorageAndroid App Development - 09 Storage
Android App Development - 09 Storage
Diego Grancini
 
Android App Development - 08 Services
Android App Development - 08 ServicesAndroid App Development - 08 Services
Android App Development - 08 Services
Diego Grancini
 
Android App Development - 07 Threading
Android App Development - 07 ThreadingAndroid App Development - 07 Threading
Android App Development - 07 Threading
Diego Grancini
 
Android App Development - 06 Fragments
Android App Development - 06 FragmentsAndroid App Development - 06 Fragments
Android App Development - 06 Fragments
Diego Grancini
 
Android App Development - 05 Action bar
Android App Development - 05 Action barAndroid App Development - 05 Action bar
Android App Development - 05 Action bar
Diego Grancini
 
Android App Development - 03 Resources
Android App Development - 03 ResourcesAndroid App Development - 03 Resources
Android App Development - 03 Resources
Diego Grancini
 
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
Diego Grancini
 
Android App Development - 01 Introduction
Android App Development - 01 IntroductionAndroid App Development - 01 Introduction
Android App Development - 01 Introduction
Diego Grancini
 

More from Diego Grancini (12)

Android App Development - 14 location, media and notifications
Android App Development - 14 location, media and notificationsAndroid App Development - 14 location, media and notifications
Android App Development - 14 location, media and notifications
 
Android App Development - 13 Broadcast receivers and app widgets
Android App Development - 13 Broadcast receivers and app widgetsAndroid App Development - 13 Broadcast receivers and app widgets
Android App Development - 13 Broadcast receivers and app widgets
 
Android App Development - 12 animations
Android App Development - 12 animationsAndroid App Development - 12 animations
Android App Development - 12 animations
 
Android App Development - 10 Content providers
Android App Development - 10 Content providersAndroid App Development - 10 Content providers
Android App Development - 10 Content providers
 
Android App Development - 09 Storage
Android App Development - 09 StorageAndroid App Development - 09 Storage
Android App Development - 09 Storage
 
Android App Development - 08 Services
Android App Development - 08 ServicesAndroid App Development - 08 Services
Android App Development - 08 Services
 
Android App Development - 07 Threading
Android App Development - 07 ThreadingAndroid App Development - 07 Threading
Android App Development - 07 Threading
 
Android App Development - 06 Fragments
Android App Development - 06 FragmentsAndroid App Development - 06 Fragments
Android App Development - 06 Fragments
 
Android App Development - 05 Action bar
Android App Development - 05 Action barAndroid App Development - 05 Action bar
Android App Development - 05 Action bar
 
Android App Development - 03 Resources
Android App Development - 03 ResourcesAndroid App Development - 03 Resources
Android App Development - 03 Resources
 
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
 
Android App Development - 01 Introduction
Android App Development - 01 IntroductionAndroid App Development - 01 Introduction
Android App Development - 01 Introduction
 

Android App Development - 11 Lists, grids, adapters, dialogs and toasts

  • 2. ListViews, GridViews, Adapters, Dialogs and Toasts A ListView or a GridView shows data in an array, a Collection or a Cursor resulting from a DB query. Contrary to what happens with the other View, the data entry is done at runtime using an Adapter that tells the system how to insert the data specifying the graphical interface of each element. To simplify this management it provides lists of specialized classes like ListActivity and ListFragment that add methods to handle the ListView without recovering its reference from the layout. ListViews and GridViews
  • 3. The main class that manages the View that make a list or a grid is BaseAdapter. The platform provides specializations of this class to simplify the creation of the view that compose a list or grid, but restrict them customization. ● ArrayAdapter<T> ● SimpleAdapter ● CursorAdapter ● SimpleCursorAdapter Adapters ListViews, GridViews, Adapters, Dialogs and Toasts
  • 4. public class ExampleAdapter extends BaseAdapter { @Override public int getCount() { return 0; } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { return null; } } BaseAdapter ListViews, GridViews, Adapters, Dialogs and Toasts
  • 5. public class ExampleAdapter extends BaseAdapter { private List<String> titles; @Override public int getCount() { if (titles != null) return titles.size(); return 0; } @Override public String getItem(int position) { return titles.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { return convertView; } } BaseAdapter ListViews, GridViews, Adapters, Dialogs and Toasts
  • 6. public class ExampleAdapter extends BaseAdapter { private List<String> titles; private LayoutInflater inflater; public ExampleAdapter(Context context) { inflater = LayoutInflater.from(context); } ... @Override public View getView(int position, View convertView, ViewGroup parent) { String title = getItem(position); convertView = inflater.inflate(R.layout.example_item, null); TextView titleView = (TextView) convertView .findViewById(R.id.example_title); titleView.setText(title); return convertView; } } BaseAdapter ListViews, GridViews, Adapters, Dialogs and Toasts
  • 7. All the times that you have to make a visible element of the list, a call is made to Adapter.getView () on the Main Thread because only this can change the graphical interface. Whether to complex View or simple View, this may affect the fluidity of the ListView and in the worst cases the entire application. The cause of this is the call to View.findViewById () that search for reference of the instance of a View. In most cases the View loaded for each element of the list is the same, then all subsequent calls to the first to retrieve the View can be eliminated by maintaining a reference to all of the Layout View. To do this you must use the View Holder Pattern. BaseAdapter - Limits ListViews, GridViews, Adapters, Dialogs and Toasts
  • 8. A ViewHolder object stores a reference of each of the Layout View in order to reuse it for all elements. public class ExampleAdapter extends BaseAdapter { private List<String> titles; private LayoutInflater inflater; ... @Override public View getView(int position, View convertView, ViewGroup parent) { String title = getItem(position); ViewHolder holder; if (convertView == null) { convertView = inflater.inflate(R.layout.example_item, null); holder = new ViewHolder(); holder.titleView = (TextView) convertView .findViewById(R.id.example_title); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.titleView.setText(title); return convertView; } static class ViewHolder { TextView titleView; } } View Holder Pattern ListViews, GridViews, Adapters, Dialogs and Toasts
  • 9. ArrayAdapter is a concrete class that allows the insertion of a simple list in a ListView. ArrayAdapter<String> itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items); By default, the text entered in the one TextView in the list is the string returned by toString(). ArrayAdapter<T> ListViews, GridViews, Adapters, Dialogs and Toasts
  • 10. SimpleAdapter (as the ArrayAdapter) is a concrete class that allows the insertion of a simple list in a ListView, but allows a greater level of customization. List<Map<String, String>> data = new ArrayList<Map<String, String>>(); data.add(new HashMap<String, String>() { { put("description", "10100"); put("title", "Torino"); } }); ... ListAdapter adapter = new SimpleAdapter(this, data, android.R.layout.simple_list_item_2, new String[] { "title", "description" }, new int[] { android.R.id.text1, android.R.id.text2 }); SimpleAdapter ListViews, GridViews, Adapters, Dialogs and Toasts
  • 11. CursorAdapter is an abstract class that simplifies the management of data from a DataBase to show them in a ListView. It is not necessary to implement the ViewHolderPattern, because the class manages the reuse of View. public class ExampleCursorAdapter extends CursorAdapter { private LayoutInflater inflater; public ExampleCursorAdapter(Context context, Cursor c, boolean autoRequery) { super(context, c, autoRequery); inflater = LayoutInflater.from(context); } @Override public void bindView(View view, Context context, Cursor cursor) { TextView titleText = (TextView) view.findViewById(R.id.example_title); String title = cursor.getString(cursor.getColumnIndex("title")); titleText.setText(title); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return inflater.inflate(R.layout.example_item, null); } } CursorAdapter ListViews, GridViews, Adapters, Dialogs and Toasts
  • 12. Once you have created the adapter, it should be assigned to the ListView or GridView with the method: listView.setAdapter(adapter); After you've assigned all'AdapterView, you no longer need to instantiate a new one: if and when the data passed to the adapter undergo a change, it is necessary and sufficient to invoke the method Adapter.notifyDataSetChanged () to apply your changes and force the update of the list. adapter.notifyDataSetChanged(); N.B.: If you change the data, but the method Adapter.notifyDataSetChanged() is not called, the system will throw an IllegalStateException. Data management ListViews, GridViews, Adapters, Dialogs and Toasts
  • 13. A Dialog is a small window that asks the user to make a selection or enter additional information. Dialog ListViews, GridViews, Adapters, Dialogs and Toasts
  • 14. The Dialog class is the base for the management of this type of objects, but the platform makes available to the specialization for certain purposes: ● AlertDialog: Dialog that shows a title, a message and up to 3 Button ● DatePickerDialog: Dialog with default layout that allows the user to select a date ● TimePickerDialog: Dialog with default layout that allows the user to select a time ● ProgressDialog: Dialog with title, message and a ProgressBar to notify the user waiting for an operation of long duration. Use of this Dialog is not recommended because it prevents the user from interacting with the application. Dialog ListViews, GridViews, Adapters, Dialogs and Toasts
  • 15. To create a Dialog you can create an instance and define the graphical interface: Dialog dialog = new Dialog(this); dialog.setContentView(R.layout.example_dialog); TextView title = (TextView) dialog.findViewById(R.id.example_title); Button close = dialog.findViewById(R.id.example_close); close.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { dialog.cancel(); } }); title.setText("Title"); dialog.show(); Dialog ListViews, GridViews, Adapters, Dialogs and Toasts
  • 16. With the introduction of the Fragment, it was added the possibility of extending DialogFragment to create Dialog. This allows you to add it to an Activity or show it like a Dialog. The DialogFragment class has pne more method than the Fragment: it's used to create the instance of Dialog in which to display the Fragment to the invocation of the method DialogFragment.show() public class ExampleDialogFragment extends DialogFragment { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Dialog dialog = new Dialog(getActivity()); dialog.setContentView(R.layout.example_dialog_fragment); return dialog; } } DialogFragment ListViews, GridViews, Adapters, Dialogs and Toasts
  • 17. An AlertDialog is composed by 3 main components: ● Title: optional ● Content: a message, a list or a custom layout ● Actions: up to 3 buttons AlertDialog ListViews, GridViews, Adapters, Dialogs and Toasts
  • 18. In order to create an AlertDialog, use an AlertDialog.Builder: AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setMessage(R.string.dialog_message).setTitle( R.string.dialog_title); // Add the buttons builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User clicked OK button } }); builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User cancelled the dialog } }); AlertDialog dialog = builder.create(); AlertDialog - Button ListViews, GridViews, Adapters, Dialogs and Toasts
  • 19. In order to create an AlertDialog, use an AlertDialog.Builder: AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.pick_color); builder.setItems(R.array.colors_array, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // The 'which' argument contains the index position // of the selected item } }); AlertDialog dialog = builder.create(); AlertDialog - List ListViews, GridViews, Adapters, Dialogs and Toasts
  • 20. In order to create an AlertDialog, use an AlertDialog.Builder: AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); mSelectedItems = new ArrayList<Integer>(); builder.setTitle(R.string.pick_color).setMultiChoiceItems( R.array.toppings, null, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { if (isChecked) { // If the user checked the item, add it to the // selected items mSelectedItems.add(which); } else if (mSelectedItems.contains(which)) { // Else, if the item is already in the array, // remove it mSelectedItems.remove(Integer.valueOf(which)); } } }); AlertDialog dialog = builder.create(); AlertDialog - MultiChoiceList ListViews, GridViews, Adapters, Dialogs and Toasts
  • 21. In order to create an AlertDialog, use an AlertDialog.Builder: AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setView(inflater.inflate(R.layout.dialog_signin, null)) // Add action buttons .setPositiveButton(R.string.signin, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog,int id){ // sign in the user ... } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id){ LoginDialogFragment.this.getDialog().cancel(); } }); AlertDialog dialog = builder.create(); AlertDialog – Custom Layout ListViews, GridViews, Adapters, Dialogs and Toasts
  • 22. If you do not want to use the Dialog API to show windows, you can assign a Dialog style to the Activity declaring it in the Manifest file: <activity android:name="com.example.test.MainActivity" android:theme="@android:style/Theme.Holo.Dialog" > </activity> Activity as a Dialog ListViews, GridViews, Adapters, Dialogs and Toasts
  • 23. A Toast shows the user a message for a short period of time without interaction. Toast Context context = getApplicationContext(); CharSequence text = "Hello toast!"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); ListViews, GridViews, Adapters, Dialogs and Toasts