ListView

Android ListView is a view which groups several items and display them in vertical scrollable list. The list items are automatically inserted to the list using an Adapter that pulls content from a source such as an array or database.
An adapter actually bridges between UI components and the data source that fill data into UI Component. Adapter can be used to supply the data to like spinner, list view, grid view etc.
Consider you have an array of strings you want to display in a ListView, initialize a new ArrayAdapter.
ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.listview, StringArray);          
Here are arguments for this constructor:
  • First argument is the application context. Most of cases, use this.
  • Second argument layout defines in XML file, having TextView for each string in the array.
  • Final argument is the array of strings which will be shown as a list.
Once you have created arrayAdapter, then simply call setAdapter() method on your listview as follows:

Listview li=(Listview)findViewById(R.id.listview1);
li.setAdapter(adapter);                            
Lets take example,

Code for MainActivity.java

String array for displaying items
String[] stateArray = { "Gujarat", "Maharashtra", "Rajasthan", "Bihar", "Delhi", "UP", "MP", "Punjab", "Tamilnadu", "Karnataka"};

ArrayAdapter to set listview items 

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, stateArray);
ListView li = (ListView) findViewById(R.id.listview1);
li.setAdapter(adapter);
      
Here listview onItemClickListener to know which item you select 
li.setOnItemClickListener(new OnItemClickListener() {
     @Override
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
         // Toast to display name you select
         Toast.makeText(MainActivity.this, parent.getItemAtPosition(position) + "", Toast.LENGTH_SHORT).show();
         }
   });

layout for listview
  <ListView
        android:id="@+id/listview1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="4dp"
        android:background="#FFFFFF"
        android:divider="#B40431"
        android:dividerHeight="2dp" >
  </ListView>

(divider means a line between each item)

Output:



On click on item, a toast will be shown named Item name.

If you want to display listview with two or more than controls, you have to use SimpleAdapter with multi-controls. Here I'm gonna explain with example.

Suppose I want to create listview with 3 controls, movie_image, movie_name and movie_casts. So first you have create simple listview layout and another layout is for listview_item.

Suppose I have listview with id listview2.
declared in java like 
ListView customListView;

Xml layout file
<ListView
        android:id="@+id/listview2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="4dp"
        android:background="#FFFFFF"
        android:divider="#B40431"
        android:dividerHeight="2dp" >

</ListView>

Layout for list_item
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linear"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:layout_weight="0.2"
        android:scaleType="fitXY"
        android:src="@drawable/ic_launcher" />

    <LinearLayout
        android:id="@+id/linear1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:layout_weight="0.8"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/name"
            android:layout_width="match_parent"
            android:layout_height="20dp"
            android:text="Name" />

        <TextView
            android:id="@+id/cast"
            android:layout_width="match_parent"
            android:layout_height="20dp"
            android:text="Cast" />
    </LinearLayout>

</LinearLayout>
 

So layout for list_item looks like this:



Define array for Movie Names
String[] nameArray = { "Jai Ho", "Heropanti", "2 States", "Main Tera Hero", "Youngistan", "Holiday", "Kick", "Ek Villain", "Singham Returns" };

Array for Movie Casts
String[] castArray = { "Salman Khan and Daisy Shah", "Tiger Shroff and Kriti Sanon", "Arjun Kapoor and Alia Bhatt",  "Varun Dhavan, Illena D'cruz and Nargis Fakhri", "Jeckie Bhagnani and Neha Sharma",  "Akshay Kumar and Sonakshi Sinha",  "Salman Khan and Jacquline Farnandiz", "Siddharth Malhotra and Shraddha Kapoor", "Ajay Devgan and Kareena Kapoor" };


Array for Movie images
int[] images = { R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d, R.drawable.e, R.drawable.f, R.drawable.g, R.drawable.h, R.drawable.i };

Put these images in res/drawble folder of your project with these same name.

Then define list with map like here aList to add map object:
List<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();

Now, you have to put value-key pair for single item in for loop and add map to list.
HashMap<String, String> map = new HashMap<String, String>();
        for (int i = 0; i < 9; i++) {
            map.put("image", Integer.toString(images[i]));
            map.put("name", nameArray[i]);
            map.put("cast", castArray[i]);
            aList.add(map);
       }


Then define from and to range: (from is same to as map's key and to field as your list_item id)
String[] from = { "image", "name", "cast" };
int[] to = { R.id.imageView, R.id.name, R.id.cast };


Then use SimpleAdapter and serAdapter() method for listview:
SimpleAdapter adapter = new SimpleAdapter(this, aList, R.layout.list_item, from, to);
customListView.setAdapter(adapter);


So the output you required is now ready.


Event to know selected item name
customListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
               // TODO Auto-generated method stub
               Toast.makeText(CustomListviewActivity.this,
                       nameArray[position], Toast.LENGTH_SHORT).show();
           }
       });
   }


Source Code: ListView

Comments

Popular posts from this blog

Get Current Location using GPS/Network Provider

MVC Architecture in Android

SQLiteDatabase (Without SqliteOpenHelper class)