Learn Android Development For Beginners

ListView

The ListView control displays a list of scrollable items vertically. It is most common control used in android development. As we have learnt about Adapters and Adapter Views previously. Adapter helps to prepare child view of each item of the list control.

The ListView control has rich properties available to set its color, font and padding etc. It also provides events to handle different scenarios like other controls.

ListView in Android

Create a new Android application and add a list view control in the activity and set some properties.

 <listview android:id="@+id/listView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawselectorontop="false"
            android:headerdividersenabled="false"
            android:footerdividersenabled="false"
            android:background="#ffffc565"
            android:divider="#a1a1a1"
            android:dividerheight="1dp" />

The divider is the line between 2 items. ListView exposes property to set divider style using android:divider and android:dividerHeight properties.

In code file for setting Adapter of ListView is very easy. Create an array of items and pass it to the ArrayAdapter and set adapter using setAdapter method of the list view. See the code below.

// Get ListView form Layout
listView = (ListView) findViewById(R.id.listView);

// Defined Array values to show in ListView
String[] values = new String[] {
        "Introduction",
        "Setting Up Environment",
        "Write Your First Program",
        "Fundamental Components",
        "Activity",
        "View",
        "Intent",
        "Fragment",
        "Content Provider",
        "Service",
        "Broadcast Receiver",
        "AndroidManifest.xml",
        "Android Application’s Folder Structure",
        "Android Common Controls and Properties",
        "Text Controls",
        "Button Controls",
        "Checkbox Control",
        "Radio Button Control",
        "Adapters and AdapterView"
};

// Define Adapter
ArrayAdapter<string> adapter = new ArrayAdapter<string>(this,
        android.R.layout.simple_list_item_1, android.R.id.text1, values);

// Assign adapter to ListView
listView.setAdapter(adapter);

As it is already described previously, the ArrayAdapter is the simplest adapter available in Android, it takes array and convert items into the view object. By default it binds the toString() value of the object to TextView. setAdapter() method of the ListView takes the adapter as a parameter.

Item Click Event

On item click event is most common event used for ListView. On click of the each item the application might need to perform some action. Android provides a way to register listener using setOnItemClickListener method. See the code below

// ListView Item Click Listener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view,
                            int position, long id) {
        int itemPosition     = position;
        String  itemValue    = (String) listView.getItemAtPosition(position);
        // Show Message
        Toast.makeText(getApplicationContext(),
                "Position :"+itemPosition+"  ListItem : " +itemValue , Toast.LENGTH_LONG)
                .show();
    }
});

The Android calls onItemClick() method when user click on the item of the ListView. It also provides the Position, View and parent of the clicked item. You can get the clicked item from specific position using listView.getItemAtPosition(position); method.

Customize List View

Customize List View in Android

As it is described in previous chapter, android allows to customize the layout of the list view. Adapter prepare a view for the each item of the ListView. Add new xml file in the layout folder and name it “list_adapater_product.xml” and design your custom UI for the ListView item in it. E.g. in given example we have Image, two TextView for title and description.

 <relativelayout xmlns:android=”http://schemas.android.com/apk/res/android”
                        android:layout_width=”fill_parent”
                        android:layout_height=”?android:attr/listPreferredItemHeight”
                        android:padding=”6dip”>
        
        <imageview android:id=”@+id/productImage”
                   android:layout_width=”wrap_content”
                   android:layout_height=”fill_parent”
                   android:layout_alignparentbottom=”true”
                   android:layout_alignparenttop=”true”
                   android:layout_marginright=”10dip”
                   android:contentdescription=”Image of the logo”
                   android:src=”@drawable/ic_launcher” />
        <textview android:id=”@+id/txtProductName”
                  android:layout_width=”fill_parent”
                  android:layout_height=”26dip”
                  android:layout_torightof=”@id/productImage”
                  android:text=”Product name”
                  android:textsize=”16sp”
                  android:textstyle=”bold”
                  android:textcolor=”#ffc77c37” />
        <textview android:id=”@+id/txtProductDesc”
                  android:layout_width=”wrap_content”
                  android:layout_height=”wrap_content”
                  android:text=”Description”
                  android:layout_torightof=”@+id/productImage”
                  android:layout_below=”@+id/txtProductName”
                  android:textsize=”10dp” />
</relativelayout>

The design of the above layout will look like this. Each product will have image, title and description.

List View Item in Android

Now create your custom adapter to set layout for each item. Create new class ProductListAdapter and extends it from BaseAdapter. Override the required method the base class.

 public class ProductListAdapter extends  BaseAdapter {
    List<product> productList = getDataForListView();
    private Context _context;
    public ProductListAdapter(Context context){
        _context = context;
    }
    @Override
    public int getCount() {
        return productList.size();
    }
    @Override
    public Product getItem(int arg0) {
        return productList.get(arg0);
    }
    @Override
    public long getItemId(int arg0) {
        return arg0;
    }
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        if(view==null)
        {
            LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.list_adapater_product, viewGroup,false);
        }
        TextView txtPName = (TextView)view.findViewById(R.id.txtProductName);
        ImageView imageView = (ImageView)view.findViewById(R.id.productImage);
        TextView txtProductDesc = (TextView)view.findViewById(R.id.txtProductDesc);
        Product chapter = productList.get(i);
        txtPName.setText(chapter.Name);
        txtProductDesc.setText(chapter.Description);
        SetImage(imageView, chapter.ProductTypeId);
        return view;
    }
    public List<product> getDataForListView() {
        List<product> productList = new ArrayList<product>();
        Product product = null;
        // Camera
        product = new Product();
        product.ProductNo = "0000001";
        product.Name = "Camera";
        product.Description = "All kind of cameras available here.";
        product.ProductTypeId = ProductType.Camera;
        productList.add(product);
        // Truck
        product = new Product();
        product.ProductNo = "0000125";
        product.Name = "Truck Service";
        product.Description = "We are the best in the transportation.";
        product.ProductTypeId = ProductType.Truck;
        productList.add(product);
        // Ticket
        product = new Product();
        product.ProductNo = "0000234";
        product.Name = "Ticket shop";
        product.Description = "Get 2 tickets free.";
        product.ProductTypeId = ProductType.Ticket;
        productList.add(product);
        // Products
        product = new Product();
        product.ProductNo = "0000054";
        product.Name = "Online Product Shop";
        product.Description = "Get 2 tickets free.";
        product.ProductTypeId = ProductType.Product;
        productList.add(product);
        return productList;
    }
    private void SetImage(ImageView image, ProductType productType)
    {
        Integer prodImageId =0;
        switch(productType){
            case Camera: {
                prodImageId = R.drawable.camera;
                break;
            }
            case Truck: {
                prodImageId = R.drawable.truck;
                break;
            }
            case Product: {
                prodImageId = R.drawable.product;
                break;
            }
            case Ticket: {
                prodImageId = R.drawable.ticket;
                break;
            }
        }
        if(prodImageId>0)
        {
            image.setImageResource(prodImageId);
        }
    }
 }

In the getView() method get the instance of LayoutInflater from content and set the layout R.layout.list_adapater_product for each item.

 LayoutInflater inflater = (LayoutInflater) _context.getSystemService(
                                                    Context.LAYOUT_INFLATER_SERVICE);
 view = inflater.inflate(R.layout.list_adapater_product, viewGroup,false);

Once custom adapter is ready, create new Activity and in its layout file add ListView control.

 <listview android:id="@+id/listView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"></listview>

In code file create the instance of ProductListAdapter class and pass the adapter using setAdapter() method of the ListView class.

 lv = (ListView)findViewById(R.id.listView);
 
 ProductListAdapter adapter = new ProductListAdapter(getApplicationContext());
 lv.setAdapter(adapter);

Register Click Event

The registration of the item click event is same as previous example. The only difference is to cast item into proper type when get it form ListView using getItemAtPosition() method.

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Product  product    = (Product) lv.getItemAtPosition(i);
            Toast.makeText(getApplicationContext(), product.Name, Toast.LENGTH_SHORT).show();
        }
    });

In above the handler only shows product name in Toast message.

ListActivity

Android also provides a ListActivity class that contains ListView control and provides a setListAdapter() method to set data.

For using ListActivity, create new Activity and inherit activity class from ListActivity Class.

 public class MyListViewActvity extends ListActivity implements AdapterView.OnItemClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        
        Cursor c = managedQuery(ContactsContract.Contacts.CONTENT_URI,
                null, null, null, ContactsContract.Contacts.DISPLAY_NAME + " ASC");

        String[] cols = new String[] {ContactsContract.Contacts.DISPLAY_NAME};

        int[] views = new int[] {android.R.id.text1};

        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_1,
                c, cols, views);

        this.setListAdapter(adapter);

        ListView lv = getListView();

        lv.setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> adView, View target, int position, long id) {
 
       Uri selectedPerson = ContentUris.withAppendedId(
                ContactsContract.Contacts.CONTENT_URI, id);

        Intent intent = new Intent(Intent.ACTION_VIEW, selectedPerson);

        startActivity(intent);

    }
 }

The setting of Adapter to ListActivity is almost same as we set it to ListView in previous example. Create an Adapter as we created SimpleCursorAdapter in above code and set the Adapter using setListAdapter() method of the ListActivity.

List Activity in Android

Handle Click Event

As we know android provides a different ways to handle events. The one way is to implement the appropriate interface for handling required event. In the above code the AdapterView.OnItemClickListener interface is implemented for handling the item click event. Override the onItemClick method to handle event and perform required action in this method.

 @Override
 public void onItemClick(AdapterView<?> adView, View target, int position, long id) {

    Uri selectedPerson = ContentUris.withAppendedId(
            ContactsContract.Contacts.CONTENT_URI, id);

    Intent intent = new Intent(Intent.ACTION_VIEW, selectedPerson);
    startActivity(intent);

 }

The ListActivity contains the ListView in it, which can be get using getListView() method of the ListActivity and set its item click listener using setOnItemClickListener() method.

 ListView lv = getListView();
 lv.setOnItemClickListener(this);

Customize ListView Activity

You can easily customization the view of ListActivity. Create custom Adapter class and extends it with any available adapter as per requirement. We have already created ProductListAdapter in this chapter, in the next example the same adapter is being used.

Create new Activity and extends the activity class with ListActivity.

 public class CustomList2Activity extends ListActivity implements AdapterView.OnItemClickListener{
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        bindList();

        ListView lv = getListView();
        lv.setOnItemClickListener(this);
    }
    
    public void bindList()
    {
        ProductListAdapter adapter = new ProductListAdapter(getApplicationContext());
        this.setListAdapter(adapter);
    }
    
    @Override
    public void onItemClick(AdapterView<?> adView, View target, int position, long id) {

       ListView lv = getListView();

       Product  product    = (Product) lv.getItemAtPosition(position);

       Toast.makeText(getApplicationContext(), product.Name, Toast.LENGTH_SHORT).show();
    }

}

The code almost same as previous examples. Create the instance of ProductListAdapter and set it using this.setListAdapter(adapter); method.

For registering the click event implements the AdapterView.OnItemClickListener interface and override its OnItemClick method.

Download Source Code

You can get the source code. Download Source Code

Other Topics

;