SlideShare une entreprise Scribd logo
1  sur  15
Android
ListView
Perfect APK
Android ListView Tutorial
Almost every Android app contains at least one ListView. ListView is one of several ways of displaying a collection of
items, and in many cases it is the most appropriate, especially in cases where the items should appear in a
specific order, or where text is displayed. In other cases you might want to consider other types of views, such as
a GridView.
In this tutorial you learn how to properly use a ListView in your Android apps, by following a ListView example for
understanding the building blocks, patterns, and best practices. Please note that the icon set for this example was
created by Design Deck.
Building Blocks
Every ListView requires the following elements, although some of the them may be hidden by using default components
provided in the Android SDK:
● Item Layout File - a ListView item XML layout file to be used by the list adapter. Sometimes layout files from the
Android SDK such as simple_list_item_1 and simple_list_item_2 are used. In this tutorial we will be using a layout
that contains an ImageView for the icon, and TextViews for the title and the description.
● Parent View Layout File - the layout file for the activity or fragment. In this tutorial this element is hidden by using the
default view of the ListFragment. For information about using a custom layout with a ListActivity or ListFragment read
Custom layout in ListActivity and ListFragment.
● Data Container - used for holding the data of a single ListView item. May be as simple as a String or a complex class.
In this tutorial we will be using a class that includes an icon, a title and a description.
● List Adapter - used for creating the views of the ListView items. In this tutorial we will be using a custom list adapter
that extends the ArrayAdapter class.
● Activity or Fragment - the ListView can be used directly or by using a ListActivity or ListFragment which are
Items Layout File
The item layout file is used by the list adapter for creating the row view. Below is an example of a ListView row:
The row view is described in the res/layout/listview_item.xml file below:
1. <?xml version="1.0" encoding="utf-8"?>
2. <!-- the parent view - provides the gray background -->
3. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
4. android:layout_width="match_parent"
5. android:layout_height="match_parent"
6. android:layout_gravity="center"
7. android:gravity="center_vertical"
8. android:background="@color/frame_background"
9. android:padding="5dp" >
Items Layout File
1.
2. <!-- the innner view - provides the white rectangle -->
3. <RelativeLayout android:layout_width="fill_parent"
4. android:layout_height="wrap_content"
5. android:background="@drawable/frame" >
6.
7. <!-- the icon view -->
8. <ImageView android:id="@+id/ivIcon"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:padding="5dp"
12. android:contentDescription="@string/icon_content_description"
13. android:scaleType="fitXY"
14. android:layout_alignParentLeft="true" />
Items Layout File
1.
2. <!-- the container view for the title and description -->
3. <RelativeLayout android:layout_width="wrap_content"
4. android:layout_height="wrap_content"
5. android:layout_toRightOf="@id/ivIcon"
6. android:layout_centerVertical="true" >
7.
8. <!-- the title view -->
9. <TextView android:id="@+id/tvTitle"
10. android:layout_width="wrap_content"
11. android:layout_height="wrap_content"
12. android:textAppearance="@android:style/TextAppearance.Medium" />
Items Layout File
1. <!-- the description view -->
2. <TextView android:id="@+id/tvDescription"
3. android:layout_below="@id/tvTitle"
4. android:layout_width="wrap_content"
5. android:layout_height="wrap_content"
6. android:textAppearance="@android:style/TextAppearance.Small" />
7. </RelativeLayout>
8.
9. </RelativeLayout>
10.
11. </RelativeLayout>
Items Layout File
The layout colors for this example are defined in the res/values/colors.xml file below:
1. <?xml version="1.0" encoding="utf-8"?>
2. <resources>
3. <color name="frame">#b4b4b4</color>
4. <color name="frame_solid">#eee</color>
5. <color name="frame_background">#bcbcbc</color>
6. </resources>
The rectangular frame in this example is defined in the res/drawable/frame.xml file below:
1. <?xml version="1.0" encoding="utf-8"?>
2. <shape xmlns:android="http://schemas.android.com/apk/res/android"
3. android:shape="rectangle" >
4.
5. <corners android:radius="2dp" />
6. <stroke android:width="1dp" android:color="@color/frame" />
7. <solid android:color="@color/frame_solid"/>
8. </shape>
Parent View Layout File
In this example I used the default view of the ListFragment. For information
about using a custom layout with a ListActivity or ListFragment read Custom
layout in ListActivity and ListFragment.
Data Container
The ListViewItem class below is used for holding the data of the ListView item:
1. public class ListViewItem {
2. public final Drawable icon; // the drawable for the ListView item ImageView
3. public final String title; // the text for the ListView item title
4. public final String description; // the text for the ListView item description
5.
6. public ListViewItem(Drawable icon, String title, String description) {
7. this.icon = icon;
8. this.title = title;
9. this.description = description;
10. }
List Adapter
The list adapter class in this example extends the ArrayAdpter class. It overrides the getView() method of the ArrayAdapter in which the row
view is created, and uses the View Holder pattern which prevents using findViewById() repeatedly. Below is the ListViewDemoAdapter
class used in this example:
1. public class ListViewDemoAdapter extends ArrayAdapter<ListViewItem> {
2.
3. public ListViewDemoAdapter(Context context, List<ListViewItem> items) {
4. super(context, R.layout.listview_item, items);
5. }
List Adapter
1. @Override
2. public View getView(int position, View convertView, ViewGroup parent) {
3. ViewHolder viewHolder;
4.
5. if(convertView == null) {
6. // inflate the GridView item layout
7. LayoutInflater inflater = LayoutInflater.from(getContext());
8. convertView = inflater.inflate(R.layout.listview_item, parent, false);
9.
10. // initialize the view holder
11. viewHolder = new ViewHolder();
12. viewHolder.ivIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
13. viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
14. viewHolder.tvDescription = (TextView) convertView.findViewById(R.id.tvDescription);
15. convertView.setTag(viewHolder);
16. } else {
17. // recycle the already inflated view
18. viewHolder = (ViewHolder) convertView.getTag();
19. }
20.
21. // update the item view
22. ListViewItem item = getItem(position);
23. viewHolder.ivIcon.setImageDrawable(item.icon);
24. viewHolder.tvTitle.setText(item.title);
25. viewHolder.tvDescription.setText(item.description);
26.
27. return convertView;
28. }
List Adapter
1. /**
2. * The view holder design pattern prevents using findViewById()
3. * repeatedly in the getView() method of the adapter.
4. *
5. * @see http://developer.android.com/training/improving-layouts/smooth-
scrolling.html#ViewHolder
6. */
7. private static class ViewHolder {
8. ImageView ivIcon;
9. TextView tvTitle;
10. TextView tvDescription;
11. }
Activity or Fragment
In this example a ListFragment is used for displaying the ListView. Using a ListActivity or ListFragment instead of a simple Activity or
Fragment saves a lot of boilerplate code such as setting the ListView, implementing the OnClickListener interface, and other code
encapsulated in convenience methods such as setListAdaper() and getListView(). Below is the ListViewDemoAdapter class used in this
example:
1. public class ListViewDemoFragment extends ListFragment {
2. private List<ListViewItem> mItems; // ListView items list
3.
4. @Override
5. public void onCreate(Bundle savedInstanceState) {
6. super.onCreate(savedInstanceState);
7.
8. // initialize the items list
9. mItems = new ArrayList<ListViewItem>();
10. Resources resources = getResources();
Activity or Fragment
1. @Override
2. public void onViewCreated(View view, Bundle savedInstanceState) {
3. super.onViewCreated(view, savedInstanceState);
4. // remove the default dividers from the ListView of the ListFragment
5. getListView().setDivider(null);
6. }
7.
8. @Override
9. public void onListItemClick(ListView l, View v, int position, long id) {
10. // retrieve theListView item
11. ListViewItem item = mItems.get(position);
12.
13. // do something
14. Toast.makeText(getActivity(), item.title, Toast.LENGTH_SHORT).show();
15. }
16. }

Contenu connexe

En vedette

Android Radio streaming
Android Radio streamingAndroid Radio streaming
Android Radio streamingAgus Haryanto
 
Android Dialogs Tutorial
Android Dialogs TutorialAndroid Dialogs Tutorial
Android Dialogs TutorialPerfect APK
 
android app development training report
android app development training reportandroid app development training report
android app development training reportRishita Jaggi
 
Data Handning with Sqlite for Android
Data Handning with Sqlite for AndroidData Handning with Sqlite for Android
Data Handning with Sqlite for AndroidJakir Hossain
 
(続) Effective SQLite for Android
(続) Effective SQLite for Android(続) Effective SQLite for Android
(続) Effective SQLite for AndroidShinobu Okano
 
Android Fast Track - Database SQLite (Kamus Tiga Bahasa)
Android Fast Track - Database SQLite (Kamus Tiga Bahasa)Android Fast Track - Database SQLite (Kamus Tiga Bahasa)
Android Fast Track - Database SQLite (Kamus Tiga Bahasa)Agus Haryanto
 
Android Sliding Menu dengan Navigation Drawer
Android Sliding Menu dengan Navigation DrawerAndroid Sliding Menu dengan Navigation Drawer
Android Sliding Menu dengan Navigation DrawerAgus Haryanto
 
Belajar Android Studio Memberi Efek animasi pada Button
Belajar Android Studio Memberi Efek animasi pada ButtonBelajar Android Studio Memberi Efek animasi pada Button
Belajar Android Studio Memberi Efek animasi pada ButtonAgus Haryanto
 
Kenalan Dengan Firebase Android
Kenalan Dengan Firebase AndroidKenalan Dengan Firebase Android
Kenalan Dengan Firebase AndroidAgus Haryanto
 
Tutorial Android Membuat Aplikasi senter Flash light
Tutorial Android Membuat Aplikasi senter Flash lightTutorial Android Membuat Aplikasi senter Flash light
Tutorial Android Membuat Aplikasi senter Flash lightAgus Haryanto
 
Android Fast Track CRUD Android PHP MySql
Android Fast Track CRUD Android PHP MySqlAndroid Fast Track CRUD Android PHP MySql
Android Fast Track CRUD Android PHP MySqlAgus Haryanto
 
Belajar Android PHP MySQL Login dengan Volley
Belajar Android PHP MySQL Login dengan VolleyBelajar Android PHP MySQL Login dengan Volley
Belajar Android PHP MySQL Login dengan VolleyAgus Haryanto
 
Adapter & ListView & ExpandalbeListView
Adapter & ListView & ExpandalbeListViewAdapter & ListView & ExpandalbeListView
Adapter & ListView & ExpandalbeListViewYuki Anzai
 
Belajar Android Membuat Katalog Produk
Belajar Android Membuat Katalog ProdukBelajar Android Membuat Katalog Produk
Belajar Android Membuat Katalog ProdukAgus Haryanto
 
Android development - ListView & Adapter
Android development - ListView & AdapterAndroid development - ListView & Adapter
Android development - ListView & AdapterLope Emano
 
Belajar Android Studio CRUD Data Mahasiswa
Belajar Android Studio CRUD Data MahasiswaBelajar Android Studio CRUD Data Mahasiswa
Belajar Android Studio CRUD Data MahasiswaAgus Haryanto
 
Introduction to Listview in Android
Introduction to Listview in AndroidIntroduction to Listview in Android
Introduction to Listview in Androidtechnoguff
 
ListView and Custom ListView on Android Development [Thai]
ListView and Custom ListView on Android Development [Thai]ListView and Custom ListView on Android Development [Thai]
ListView and Custom ListView on Android Development [Thai]Somkiat Khitwongwattana
 

En vedette (18)

Android Radio streaming
Android Radio streamingAndroid Radio streaming
Android Radio streaming
 
Android Dialogs Tutorial
Android Dialogs TutorialAndroid Dialogs Tutorial
Android Dialogs Tutorial
 
android app development training report
android app development training reportandroid app development training report
android app development training report
 
Data Handning with Sqlite for Android
Data Handning with Sqlite for AndroidData Handning with Sqlite for Android
Data Handning with Sqlite for Android
 
(続) Effective SQLite for Android
(続) Effective SQLite for Android(続) Effective SQLite for Android
(続) Effective SQLite for Android
 
Android Fast Track - Database SQLite (Kamus Tiga Bahasa)
Android Fast Track - Database SQLite (Kamus Tiga Bahasa)Android Fast Track - Database SQLite (Kamus Tiga Bahasa)
Android Fast Track - Database SQLite (Kamus Tiga Bahasa)
 
Android Sliding Menu dengan Navigation Drawer
Android Sliding Menu dengan Navigation DrawerAndroid Sliding Menu dengan Navigation Drawer
Android Sliding Menu dengan Navigation Drawer
 
Belajar Android Studio Memberi Efek animasi pada Button
Belajar Android Studio Memberi Efek animasi pada ButtonBelajar Android Studio Memberi Efek animasi pada Button
Belajar Android Studio Memberi Efek animasi pada Button
 
Kenalan Dengan Firebase Android
Kenalan Dengan Firebase AndroidKenalan Dengan Firebase Android
Kenalan Dengan Firebase Android
 
Tutorial Android Membuat Aplikasi senter Flash light
Tutorial Android Membuat Aplikasi senter Flash lightTutorial Android Membuat Aplikasi senter Flash light
Tutorial Android Membuat Aplikasi senter Flash light
 
Android Fast Track CRUD Android PHP MySql
Android Fast Track CRUD Android PHP MySqlAndroid Fast Track CRUD Android PHP MySql
Android Fast Track CRUD Android PHP MySql
 
Belajar Android PHP MySQL Login dengan Volley
Belajar Android PHP MySQL Login dengan VolleyBelajar Android PHP MySQL Login dengan Volley
Belajar Android PHP MySQL Login dengan Volley
 
Adapter & ListView & ExpandalbeListView
Adapter & ListView & ExpandalbeListViewAdapter & ListView & ExpandalbeListView
Adapter & ListView & ExpandalbeListView
 
Belajar Android Membuat Katalog Produk
Belajar Android Membuat Katalog ProdukBelajar Android Membuat Katalog Produk
Belajar Android Membuat Katalog Produk
 
Android development - ListView & Adapter
Android development - ListView & AdapterAndroid development - ListView & Adapter
Android development - ListView & Adapter
 
Belajar Android Studio CRUD Data Mahasiswa
Belajar Android Studio CRUD Data MahasiswaBelajar Android Studio CRUD Data Mahasiswa
Belajar Android Studio CRUD Data Mahasiswa
 
Introduction to Listview in Android
Introduction to Listview in AndroidIntroduction to Listview in Android
Introduction to Listview in Android
 
ListView and Custom ListView on Android Development [Thai]
ListView and Custom ListView on Android Development [Thai]ListView and Custom ListView on Android Development [Thai]
ListView and Custom ListView on Android Development [Thai]
 

Dernier

Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 

Dernier (20)

Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 

Android ListView Tutorial

  • 2. Android ListView Tutorial Almost every Android app contains at least one ListView. ListView is one of several ways of displaying a collection of items, and in many cases it is the most appropriate, especially in cases where the items should appear in a specific order, or where text is displayed. In other cases you might want to consider other types of views, such as a GridView. In this tutorial you learn how to properly use a ListView in your Android apps, by following a ListView example for understanding the building blocks, patterns, and best practices. Please note that the icon set for this example was created by Design Deck.
  • 3. Building Blocks Every ListView requires the following elements, although some of the them may be hidden by using default components provided in the Android SDK: ● Item Layout File - a ListView item XML layout file to be used by the list adapter. Sometimes layout files from the Android SDK such as simple_list_item_1 and simple_list_item_2 are used. In this tutorial we will be using a layout that contains an ImageView for the icon, and TextViews for the title and the description. ● Parent View Layout File - the layout file for the activity or fragment. In this tutorial this element is hidden by using the default view of the ListFragment. For information about using a custom layout with a ListActivity or ListFragment read Custom layout in ListActivity and ListFragment. ● Data Container - used for holding the data of a single ListView item. May be as simple as a String or a complex class. In this tutorial we will be using a class that includes an icon, a title and a description. ● List Adapter - used for creating the views of the ListView items. In this tutorial we will be using a custom list adapter that extends the ArrayAdapter class. ● Activity or Fragment - the ListView can be used directly or by using a ListActivity or ListFragment which are
  • 4. Items Layout File The item layout file is used by the list adapter for creating the row view. Below is an example of a ListView row: The row view is described in the res/layout/listview_item.xml file below: 1. <?xml version="1.0" encoding="utf-8"?> 2. <!-- the parent view - provides the gray background --> 3. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 4. android:layout_width="match_parent" 5. android:layout_height="match_parent" 6. android:layout_gravity="center" 7. android:gravity="center_vertical" 8. android:background="@color/frame_background" 9. android:padding="5dp" >
  • 5. Items Layout File 1. 2. <!-- the innner view - provides the white rectangle --> 3. <RelativeLayout android:layout_width="fill_parent" 4. android:layout_height="wrap_content" 5. android:background="@drawable/frame" > 6. 7. <!-- the icon view --> 8. <ImageView android:id="@+id/ivIcon" 9. android:layout_width="wrap_content" 10. android:layout_height="wrap_content" 11. android:padding="5dp" 12. android:contentDescription="@string/icon_content_description" 13. android:scaleType="fitXY" 14. android:layout_alignParentLeft="true" />
  • 6. Items Layout File 1. 2. <!-- the container view for the title and description --> 3. <RelativeLayout android:layout_width="wrap_content" 4. android:layout_height="wrap_content" 5. android:layout_toRightOf="@id/ivIcon" 6. android:layout_centerVertical="true" > 7. 8. <!-- the title view --> 9. <TextView android:id="@+id/tvTitle" 10. android:layout_width="wrap_content" 11. android:layout_height="wrap_content" 12. android:textAppearance="@android:style/TextAppearance.Medium" />
  • 7. Items Layout File 1. <!-- the description view --> 2. <TextView android:id="@+id/tvDescription" 3. android:layout_below="@id/tvTitle" 4. android:layout_width="wrap_content" 5. android:layout_height="wrap_content" 6. android:textAppearance="@android:style/TextAppearance.Small" /> 7. </RelativeLayout> 8. 9. </RelativeLayout> 10. 11. </RelativeLayout>
  • 8. Items Layout File The layout colors for this example are defined in the res/values/colors.xml file below: 1. <?xml version="1.0" encoding="utf-8"?> 2. <resources> 3. <color name="frame">#b4b4b4</color> 4. <color name="frame_solid">#eee</color> 5. <color name="frame_background">#bcbcbc</color> 6. </resources> The rectangular frame in this example is defined in the res/drawable/frame.xml file below: 1. <?xml version="1.0" encoding="utf-8"?> 2. <shape xmlns:android="http://schemas.android.com/apk/res/android" 3. android:shape="rectangle" > 4. 5. <corners android:radius="2dp" /> 6. <stroke android:width="1dp" android:color="@color/frame" /> 7. <solid android:color="@color/frame_solid"/> 8. </shape>
  • 9. Parent View Layout File In this example I used the default view of the ListFragment. For information about using a custom layout with a ListActivity or ListFragment read Custom layout in ListActivity and ListFragment.
  • 10. Data Container The ListViewItem class below is used for holding the data of the ListView item: 1. public class ListViewItem { 2. public final Drawable icon; // the drawable for the ListView item ImageView 3. public final String title; // the text for the ListView item title 4. public final String description; // the text for the ListView item description 5. 6. public ListViewItem(Drawable icon, String title, String description) { 7. this.icon = icon; 8. this.title = title; 9. this.description = description; 10. }
  • 11. List Adapter The list adapter class in this example extends the ArrayAdpter class. It overrides the getView() method of the ArrayAdapter in which the row view is created, and uses the View Holder pattern which prevents using findViewById() repeatedly. Below is the ListViewDemoAdapter class used in this example: 1. public class ListViewDemoAdapter extends ArrayAdapter<ListViewItem> { 2. 3. public ListViewDemoAdapter(Context context, List<ListViewItem> items) { 4. super(context, R.layout.listview_item, items); 5. }
  • 12. List Adapter 1. @Override 2. public View getView(int position, View convertView, ViewGroup parent) { 3. ViewHolder viewHolder; 4. 5. if(convertView == null) { 6. // inflate the GridView item layout 7. LayoutInflater inflater = LayoutInflater.from(getContext()); 8. convertView = inflater.inflate(R.layout.listview_item, parent, false); 9. 10. // initialize the view holder 11. viewHolder = new ViewHolder(); 12. viewHolder.ivIcon = (ImageView) convertView.findViewById(R.id.ivIcon); 13. viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle); 14. viewHolder.tvDescription = (TextView) convertView.findViewById(R.id.tvDescription); 15. convertView.setTag(viewHolder); 16. } else { 17. // recycle the already inflated view 18. viewHolder = (ViewHolder) convertView.getTag(); 19. } 20. 21. // update the item view 22. ListViewItem item = getItem(position); 23. viewHolder.ivIcon.setImageDrawable(item.icon); 24. viewHolder.tvTitle.setText(item.title); 25. viewHolder.tvDescription.setText(item.description); 26. 27. return convertView; 28. }
  • 13. List Adapter 1. /** 2. * The view holder design pattern prevents using findViewById() 3. * repeatedly in the getView() method of the adapter. 4. * 5. * @see http://developer.android.com/training/improving-layouts/smooth- scrolling.html#ViewHolder 6. */ 7. private static class ViewHolder { 8. ImageView ivIcon; 9. TextView tvTitle; 10. TextView tvDescription; 11. }
  • 14. Activity or Fragment In this example a ListFragment is used for displaying the ListView. Using a ListActivity or ListFragment instead of a simple Activity or Fragment saves a lot of boilerplate code such as setting the ListView, implementing the OnClickListener interface, and other code encapsulated in convenience methods such as setListAdaper() and getListView(). Below is the ListViewDemoAdapter class used in this example: 1. public class ListViewDemoFragment extends ListFragment { 2. private List<ListViewItem> mItems; // ListView items list 3. 4. @Override 5. public void onCreate(Bundle savedInstanceState) { 6. super.onCreate(savedInstanceState); 7. 8. // initialize the items list 9. mItems = new ArrayList<ListViewItem>(); 10. Resources resources = getResources();
  • 15. Activity or Fragment 1. @Override 2. public void onViewCreated(View view, Bundle savedInstanceState) { 3. super.onViewCreated(view, savedInstanceState); 4. // remove the default dividers from the ListView of the ListFragment 5. getListView().setDivider(null); 6. } 7. 8. @Override 9. public void onListItemClick(ListView l, View v, int position, long id) { 10. // retrieve theListView item 11. ListViewItem item = mItems.get(position); 12. 13. // do something 14. Toast.makeText(getActivity(), item.title, Toast.LENGTH_SHORT).show(); 15. } 16. }