Tuesday, February 25, 2014

Inflating a ListView

We need to inflate a listview in 2 cases.

1. When we want to display a listview at run time
2. When we need a custom listview

We will see both the cases with examples.
Case 1: In this example we will  inflate a listview. See how

Android Layout File
File: res/layout/main.xml
<linearlayout 
android:id="@+id/layout1" 
android:layout_height="match_parent" 
android:layout_width="match_parent" 
android:orientation="vertical" 
xmlns:android="http://schemas.android.com/apk/res/android">

   <textview 
android:id="@+id/namelabel" 
android:layout_height="wrap_content" 
android:layout_width="wrap_content" 
android:text="Text Paragraph.">
    </textview> 
</linearlayout>
We have another layout file activity_main having listview in it.
File: res/layout/activity_main.xml
<ListView
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/listview"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:cacheColorHint="#EEEEEE"
 android:background="#CCCCCC" />
We are going to inflate layout activity_main in our main activity.Our main inflatelistview activity is as follows.
package com.example.inflatelistview;

import java.util.ArrayList;

import java.util.HashMap;
import java.util.List;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.Menu;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class inflatelistview extends Activity {
 LinearLayout ILayout;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);

     final LayoutInflater  inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        ListView t = (ListView)inflater.inflate(R.layout.activity_main,null);
        
        ILayout = (LinearLayout)findViewById(R.id.layout1);
        ILayout.addView(t);
     String[] values = new String[] { "Item1","Item2","Item3","Item4"};

     final ArrayList list = new ArrayList();
     for (int i = 0; i < values.length; ++i) {
       list.add(values[i]);
     }
     final OurArrayAdapter adapter = new OurArrayAdapter(this,
         android.R.layout.simple_list_item_1, list);
     t.setAdapter(adapter);

     
   }

   private class OurArrayAdapter extends ArrayAdapter {

     HashMap MapValue = new HashMap();

     public OurArrayAdapter(Context context, int textViewResourceId,
         List objects) {
       super(context, textViewResourceId, objects);
       for (int i = 0; i < objects.size(); ++i) {
         MapValue.put(objects.get(i), i);
       }
     }

     @Override
     public long getItemId(int position) {
       String item = getItem(position);
       return MapValue.get(item);
     }

     @Override
     public boolean hasStableIds() {
       return true;
     }

   }

 } 

The same thing we can do without inflating in a simple way by including listview in our main.xml and adding
final ListView listview = (ListView) findViewById(R.id.listview); 

instead of

final LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ListView t = (ListView)inflater.inflate(R.layout.activity_main,null);
ILayout = (LinearLayout)findViewById(R.id.layout1);
ILayout.addView(t); 

Case 2: We will create a custom listview having a image & text in it. To create a custom listview,we need to create custom adapter. In this example we will use arrayadapter for easy understanding. You will need 2 layout files. One, main.xml, will define the attributes of the ListView. The other, mainlvitem.xml, will be the layout of each individual row in the ListView.

 File: res/layout/main.xml:
<ListView
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/listview"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:cacheColorHint="#EEEEEE"
 android:background="#CCCCCC" />
Next File,res/layout/mainlvitem.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:orientation="horizontal"
 android:paddingLeft="4dp"
 android:paddingRight="15dp"
 android:paddingTop="13dp"
 android:paddingBottom="13dp"
 android:weightSum="1"
 android:background="#FFFFFF" >

 <ImageView
  android:id="@+id/img"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_gravity="center_vertical"
  android:layout_weight="0.10" />

 <TextView
  android:id="@+id/txt"
  android:layout_width="0dp"
  android:layout_height="wrap_content"
  android:layout_gravity="center"
  android:gravity="left"
  android:layout_weight="0.90"
  android:paddingLeft="10dp"
  android:textColor="#222222"/>
</LinearLayout>
Now the main activity is
package com.example.inflatelistview;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
 
public class customlistview extends Activity {
 
// We will declare some variables within the class, but outside of any method so that
// any method can use them.
 
ListView lv; // The ListView we will be building
 
// A String[] array that will hold the names of the items.
String[] mItems = { "Item1", "Item2", "Item3" };
 
// An Integer[] array that will hold the resource drawables that will be displayed as icons.
 Integer[] mIcons =
 { R.drawable.ic_launcher, R.drawable.ic_launcher, R.drawable.ic_launcher };
 
// -----------------------------------------------
// onCreate()
// -----------------------------------------------
 
 @Override
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
 
    // Here we will take the ListView that we declared in activity_main layout
    
    lv = (ListView) findViewById(R.id.listview);
 
    // Instead of using a regular ArrayAdapter to pull Strings from an array,
    // we will create a custom ArrayAdapter below. This bit of code sets the adapter
    // of our ListView, lv, to our customer adapter.
    ArrayAdapter adapter = new CustomAdapter(this, R.layout.mainlvitem, mItems);
    lv.setAdapter(adapter);
 
 } // end onCreate
 
// -----------------------------------------------
// This is our custom ArrayAdapter, CustomAdapter
// -----------------------------------------------
 
 public class CustomAdapter extends ArrayAdapter
    {
        public CustomAdapter(Context context, int textViewResourceId, String[] objects)
        {
            super(context, textViewResourceId, objects);
        }
 
        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            // Inflate the layout, mainlvitem.xml, in each row.
            LayoutInflater inflater = customlistview.this.getLayoutInflater();
            View row = inflater.inflate(R.layout.mainlvitem, parent, false);
 
            // Declare and define the TextView, "item." This is where
            // the name of each item will appear.
            TextView item = (TextView)row.findViewById(R.id.txt);
            item.setText(mItems[position]);
 
            // Declare and define the TextView, "icon." This is where
            // the icon in each row will appear.
            ImageView icon=(ImageView)row.findViewById(R.id.img);
            icon.setImageResource(mIcons[position]);
 
            return row;
        }
    } // end CustomAdapter
}

We have used default images which comes with drawable folder ic_launcher in this program.However you can use any other image as you want. You need to put those images in appropriate folder.

10 comments:

  1. Excellent and clear explanation. Very helpful.

    ReplyDelete
  2. Hello. This post couldn’t be written any better! Reading this post reminds me of my previous roommate. He always kept chatting about this.
    safety course in chennai

    ReplyDelete
  3. Thank You! For sharing such a great article, It's been a amazing article.
    It's provide lot's of information, I really enjoyed to read this.
    I hope, i will get these kinds of information on a regular basis from your side.
    I follows your site, and share your's content because it is so much useful.

    Source: Play Sports Free
    Keyword: Way to Earn Money
    Read: Wrestle Mania 36
    Watch: Wrestling Video

    ReplyDelete