android listview tutorial

13
Android ListView Tutorial By - Javatechig.com

Upload: javatechig

Post on 29-Dec-2015

57 views

Category:

Documents


0 download

DESCRIPTION

This post will walk you through Android ListView Tutorial for building simple and customized ListView using different Android adapters.List is one of the most common UI patterns, which is being used extensively to display the collection of data elements in rows. In android ListView is a view group that displays a list of scrollable items. The list items are automatically inserted to the list using an Adapter that pulls content from a source such as an array.

TRANSCRIPT

Android ListView Tutorial

By - Javatechig.com

Android ListView TutorialTable of Contents

1. What is Adapter?

2. Building ListView   using   ArrayAdapter

3. Building ListView   using Custom Adapter

3.1. Create your custom row layout

3.2. Writing a custom adapter

3.3. Putting it all together

3.4. Output

4. Customizing ListView

4.1. Change ListView selection colour in Android

5. How to change the divider color in the ListView?

5.1. Changing ListView   divider color and height

5.2. Using a drawable for ListView divider

5.3.   Changing   ListView   divider color pragmatically

6. References

This post will walk you through Android ListView Tutorial for building simple and customized ListView using

different Android adapters.

List is one of the most common UI patterns, which is being used extensively to display the collection of data elements

in rows. In android ListView is a view group that displays a list of scrollable items. The list items are automatically

inserted to the list using an Adapter that pulls content from a source such as an array.

1. What is Adapter?Adapter is basically bridge between UI components and the data source that fill data into UI Component. Adapter is

used to supply the data to like spinner, list view, grid view etc. For example, we can create a list view from xml layout

without data, and using adapter we can supply data sets to list view.

If you look at the above images you will certainly get an idea of list view. This kind of customizable list views can be

done using an adapter.

2. Building ListView using ArrayAdapterThis is the simplest way we can create a simple default styled list view from array of elements. To do this there are

three things to concentrate,

1. Find out what data you want to display in list: For our example, I am considered taking a static array of

strings. But for complex scenarios it can be a response from server, or data fetched from database.

2. Declare the list view object in your xml layout: ListView is the user interface element we are using to

represent data to user. So in my example, the layout contains a list view. Make sure you provide an appropriate

id.

3. Now finally, feed the list view with the data sets: For this we use adapters. We can always customize our

adapter, but for to start let’s make it simple. I am using Array adapter class available in android.

Here is how my layout file looks like

?

1234567891011121314

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".ListActivity" >

<ListViewandroid:id="@+id/months_list"android:layout_width="match_parent"android:layout_height="wrap_content" ></ListView>

</LinearLayout>

ListActivity.java

?

1234567891011121314151617

package com.javatechig.droid.ui;

import android.os.Bundle;import android.app.Activity;import android.widget.ArrayAdapter;import android.widget.ListView;

public class ListActivity extends Activity {

    // Initialize the array    String[] monthsArray = { "JAN", "FEB", "MAR", "APR", "MAY", "JUNE", "JULY", "AUG", "SEPT", "OCT", "NOV", "DEC" };

    // Declare the UI components    private ListView monthsListView;

1819202122232425262728293031323334353637383940

    private ArrayAdapter arrayAdapter;

    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_list);

        // Initialize the UI components        monthsListView = (ListView) findViewById(R.id.months_list);        // For this moment, you have ListView where you can display a list.        // But how can we put this data set to the list?        // This is where you need an Adapter

        // context - The current context.        // resource - The resource ID for a layout file containing a layout                // to use when instantiating views.        // From the third parameter, you plugged the data set to adapter        arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, monthsArray);

        // By using setAdapter method, you plugged the ListView with adapter        monthsListView.setAdapter(arrayAdapter);    }}

Output of the above code is

3. Building ListView using Custom AdapterIf you have followed my previous example, then you are ready with a simple list which using ArrayAdapter. Now it’s

the time to create something fancy. In this section of tutorial, you will find steps to customize a list using custom

adapters.

In this above example I am displaying a new list items. Below is my NewsItem object

?

12345678910111213141516171819202122232425262728293031

public class NewsItem {

    private String headline;    private String reporterName;    private String date;

    public String getHeadline() {        return headline;    }

    public void setHeadline(String headline) {        this.headline = headline;    }

    public String getReporterName() {        return reporterName;    }

    public void setReporterName(String reporterName) {        this.reporterName = reporterName;    }

    public String getDate() {        return date;    }

    public void setDate(String date) {        this.date = date;    }

    @Override    public String toString() {        return "[ headline=" + headline + ", reporter Name=" +                reporterName + " , date=" + date + "]";    }}

3.1. Create your custom row layoutI have created a simple layout as shown in the image below, which holds news headline, reported name and date.

list_row_layout.xml

?

123456

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:minHeight="50dp"    android:orientation="horizontal"

7891011121314151617181920212223242526272829303132333435363738

    android:padding="5dip" >

    <TextView        android:id="@+id/title"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text=""        android:textStyle="bold"        android:typeface="sans" />

    <TextView        android:id="@+id/reporter"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@id/title"        android:layout_marginTop="5dip"        android:text=""        android:textColor="#343434"        android:textSize="12sp" />

    <TextView        android:id="@+id/date"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignBaseline="@+id/reporter"        android:layout_alignBottom="@+id/reporter"        android:layout_alignParentRight="true"        android:text=""        android:textColor="#343434"        android:textSize="12sp" />

</RelativeLayout>

3.2. Writing a custom adapterCustomListAdapter.java

?

1234567891011

public class CustomListAdapter extends BaseAdapter {

    private ArrayList listData;

    private LayoutInflater layoutInflater;

    public CustomListAdapter(Context context, ArrayList listData) {        this.listData = listData;        layoutInflater = LayoutInflater.from(context);    }

    @Override    public int getCount() {

121314151617181920212223242526272829303132333435363738394041424344454647484950515253

        return listData.size();    }

    @Override    public Object getItem(int position) {        return listData.get(position);    }

    @Override    public long getItemId(int position) {        return position;    }

    public View getView(int position, View convertView, ViewGroup parent) {        ViewHolder holder;        if (convertView == null) {            convertView = layoutInflater.inflate(R.layout.list_row_layout, null);            holder = new ViewHolder();            holder.headlineView = (TextView) convertView.findViewById(R.id.title);            holder.reporterNameView = (TextView) convertView.findViewById(R.id.reporter);            holder.reportedDateView = (TextView) convertView.findViewById(R.id.date);            convertView.setTag(holder);        } else {            holder = (ViewHolder) convertView.getTag();        }

        holder.headlineView.setText(listData.get(position).getHeadline());        holder.reporterNameView.setText("By, " + listData.get(position).getReporterName());        holder.reportedDateView.setText(listData.get(position).getDate());

        return convertView;    }

    static class ViewHolder {        TextView headlineView;        TextView reporterNameView;        TextView reportedDateView;    }

}

3.3. Putting it all togetherNow we are ready with adapter and layout. Let’s put all of them together and build a custom list.

activity_main.xml : This is my main activity layout. For making this example simpler, I just have a ListView inside a

LinearLayout.

?

12345678910111213

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >

    <ListView        android:id="@+id/custom_list"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:dividerHeight="1dp" />

</LinearLayout>

Here my activity class MainActivity.java where I am initializing list view and adapter

?

123456789101112131415161718

public class MainActivity extends Activity {

    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);

        ArrayList image_details = getListData();        final ListView lv1 = (ListView) findViewById(R.id.custom_list);        lv1.setAdapter(new CustomListAdapter(this, image_details));        lv1.setOnItemClickListener(new OnItemClickListener() {

            @Override            public void onItemClick(AdapterView<?> a, View v, int position, long id) {                Object o = lv1.getItemAtPosition(position);                NewsItem newsData = (NewsItem) o;                Toast.makeText(MainActivity.this, "Selected :" + " " + newsData, Toast.LENGTH_LONG).show();            }

        });

    }

    private ArrayList getListData() {        ArrayList results = new ArrayList();        NewsItem newsData = new NewsItem();        newsData.setHeadline("Dance of Democracy");        newsData.setReporterName("Pankaj Gupta");        newsData.setDate("May 26, 2013, 13:35");        results.add(newsData);

1920212223242526272829303132333435363738394041

        newsData = new NewsItem();        newsData.setHeadline("Major Naxal attacks in the past");        newsData.setReporterName("Pankaj Gupta");        newsData.setDate("May 26, 2013, 13:35");        results.add(newsData);

        newsData = new NewsItem();        newsData.setHeadline("BCCI suspends Gurunath pending inquiry ");        newsData.setReporterName("Rajiv Chandan");        newsData.setDate("May 26, 2013, 13:35");        results.add(newsData);

        newsData = new NewsItem();        newsData.setHeadline("Life convict can`t claim freedom after 14 yrs: SC");        newsData.setReporterName("Pankaj Gupta");        newsData.setDate("May 26, 2013, 13:35");        results.add(newsData);

        newsData = new NewsItem();        newsData.setHeadline("Indian Army refuses to share info on soldiers mutilated at LoC");        newsData.setReporterName("Pankaj Gupta");        newsData.setDate("May 26, 2013, 13:35");        results.add(newsData);

        newsData = new NewsItem();        newsData.setHeadline("French soldier stabbed; link to Woolwich attack being probed");        newsData.setReporterName("Sudeep Nanda");        newsData.setDate("May 26, 2013, 13:35");        results.add(newsData);

        return results;    }}

424344454647484950515253545556575859

3.4. Output