Tag Archives: ListView

featured_img

Good morning folks ! Here I am going to show you simple and awesome tutorial on Custom List view using Base adapter with Text and images .This tutorial is going to be awesome because this is the starting of your first chat application like Hike and Whatsapp, how to develop a chat application I’ll provide simple tutorial on it but first lets start with basic need. Lets dig inside-

In this tutorial I have taken three Text View and one Image View for profile pictures. Lets start quickly.

NOTE – If you got error after importing this code then just delete value-11 and value-14 folders and remove extended ActionBarActivity and do it to Activity and import it.

Download Code

Lets do the code , firstly start the code with designing part  that’s my personal point of view that always start with designing part i.e. XML . Many developers also do the same. So take new Android project and name whatever your is and go to your Layout folder and double click activity_main.xml and paste the following code.

In this xml file I have taken a simple ListView that going to show us on launching our application.

activity_main.xml

<?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/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
     />
</LinearLayout>

After that we should go to strings.xml file in our values folder and take arrays for listview .

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Hike</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>

    
    
    
    
    
     <!-- Names -->
    <string-array name="names_array">
        <item>Johnny Depp</item>
        <item>Benicio Del Toro</item>
        <item>Morgan Freeman</item>
        <item>Christian Bale</item>
        <item>Leonardo DiCaprio</item>
        <item>Salman Khan</item>
       <item> Brad Pitt</item>
    </string-array>

    <!-- Pictures -->
    <array name="pics_array">
        <item>@drawable/img1</item>
        <item>@drawable/img2</item>
        <item>@drawable/img3</item>
        <item>@drawable/img4</item>
        <item>@drawable/img5</item>
        <item>@drawable/img6</item>
          <item>@drawable/img7</item>
    </array>

    <!-- Status -->
    <string-array name="sta_array">
        <item>love Bohemia</item>
        <item>Available</item>
        <item>Busy</item>
        <item>In a meeting</item>
        <item>At work</item>
        <item>At gym</item>
        <item>At the movies</item>
    </string-array>

    <!-- contact type -->
    <string-array name="contact_array">
        <item>12:30am</item>
        <item>11:30am</item>
        <item>1:00pm</item>
        <item>12:51pm</item>
        <item>08:12am</item>
        <item>06:09am</item>
        <item>13:56pm</item>
    </string-array>
</resources>

Now take another XML file for custom View that you want in your android application . This View is something like if you want to show images,text,radio button,buttons in your list view than you have to take new XML file and you have to make your view which we going to embed in our simple List View.

Here we take list_item.xml for this View and in it I have taken ImageView,TextView .

<?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="fill_parent"
    android:padding="2dp" >

    <ImageView
        android:id="@+id/pic"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:contentDescription="desc"
        android:paddingLeft="10dp"
        android:paddingRight="10dp" />

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_toRightOf="@+id/pic"
        android:paddingBottom="10dp"
        android:text="head"
        android:textStyle="bold"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/sta"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/name"
        android:layout_below="@+id/name"
        android:text="status"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/contact"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/name"
        android:layout_alignBottom="@+id/name"
        android:layout_alignParentRight="true"
        android:text="online"
        android:textSize="16sp" />

</RelativeLayout>

Now Coding part , In this part I have taken a three java files in our src folder , get started with it. I have taken a Bean class namely RowItem.java .What basically a Bean class is that it is a reusable software component it encapsulate many objects into one and we can access this objects from multiple places , also maintenance become so easy .Its upto you that you want to take this Bean Class or not.

RowItem.java

package androidarena.customlistviewwhatsapplike;

public class RowItem {

	 private String member_name;
	 private int profile_pic_id;
	 private String status;
	 private String contactType;

	 public RowItem(String member_name, int profile_pic_id, String status,
	   String contactType) {

	  this.member_name = member_name;
	  this.profile_pic_id = profile_pic_id;
	  this.status = status;
	  this.contactType = contactType;
	 }

	 public String getMember_name() {
	  return member_name;
	 }

	 public void setMember_name(String member_name) {
	  this.member_name = member_name;
	 }

	 public int getProfile_pic_id() {
	  return profile_pic_id;
	 }

	 public void setProfile_pic_id(int profile_pic_id) {
	  this.profile_pic_id = profile_pic_id;
	 }

	 public String getStatus() {
	  return status;
	 }

	 public void setStatus(String status) {
	  this.status = status;
	 }

	 public String getContactType() {
	  return contactType;
	 }

	 public void setContactType(String contactType) {
	  this.contactType = contactType;
	 }

	}

After this make a CustomAdapter.java class in your project under src folder and paste the following code.This class should extends Baseadapter and thus you should implements rest of the override methods .

Steps to be followed

1). Class Should extends Baseadapter and implements overrided methods .

2). Take inner class ViewHolder and declare some TextView and ImageView respectively .

3).  Take LayoutInflator object and ViewHolder object.

4). Write a condition for Views and setImageResources and setText .

CustomAdapter.java

package androidarena.customlistviewwhatsapplike;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomAdapter extends BaseAdapter {

 Context context;
 List<RowItem> rowItems;

 CustomAdapter(Context context, List<RowItem> rowItems) {
  this.context = context;
  this.rowItems = rowItems;
 }

 @Override
 public int getCount() {
  return rowItems.size();
 }

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

 @Override
 public long getItemId(int position) {
  return rowItems.indexOf(getItem(position));
 }

 /* private view holder class */
 private class ViewHolder {
  ImageView profile_pic;
  TextView member_name;
  TextView status;
  TextView contactType;
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {

  ViewHolder holder = null;

  LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
  
  
  if (convertView == null) {
	  
   convertView = mInflater.inflate(R.layout.list_item, null);
   holder = new ViewHolder();

   holder.member_name = (TextView) convertView
     .findViewById(R.id.name);
   holder.profile_pic = (ImageView) convertView
     .findViewById(R.id.pic);
   holder.status = (TextView) convertView.findViewById(R.id.sta);
   holder.contactType = (TextView) convertView
     .findViewById(R.id.contact);

   RowItem row_pos = rowItems.get(position);

   holder.profile_pic.setImageResource(row_pos.getProfile_pic_id());
   holder.member_name.setText(row_pos.getMember_name());
   holder.status.setText(row_pos.getStatus());
   holder.contactType.setText(row_pos.getContactType());

   convertView.setTag(holder);
  } else {
   holder = (ViewHolder) convertView.getTag();
  }

  return convertView;
 }

}

Now take MainActivity.java file and include the below code there .

package androidarena.customlistviewwhatsapplike;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class MainActivity extends Activity implements OnItemClickListener {

 String[] member_names;
 TypedArray profile_pics;
 String[] statues;
 String[] contactType;

 List<RowItem> rowItems;
 ListView mylistview;

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

  rowItems = new ArrayList<RowItem>();

  member_names = getResources().getStringArray(R.array.names_array);

  profile_pics = getResources().obtainTypedArray(R.array.pics_array);

  statues = getResources().getStringArray(R.array.sta_array);

  contactType = getResources().getStringArray(R.array.contact_array);

  
  
  
  for (int i = 0; i < member_names.length; i++) {
   RowItem item = new RowItem(member_names[i],
     profile_pics.getResourceId(i, -1), statues[i],
     contactType[i]);
   rowItems.add(item);
  }

  mylistview = (ListView) findViewById(R.id.list);
  CustomAdapter adapter = new CustomAdapter(this, rowItems);
  mylistview.setAdapter(adapter);
  profile_pics.recycle();
  mylistview.setOnItemClickListener(this);

 }

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

  String member_name = rowItems.get(position).getMember_name();
  Toast.makeText(getApplicationContext(), "" + member_name,
    Toast.LENGTH_SHORT).show();
 }

}

 Below hierarchy should be like this –

explore_IDE

hierarchy of project

Now Run your project and see your output in the emulator .

Output- 

output_hike

custom listview output

For more query and suggestions , do comment below ,love to hear from you . Thank You 😛

 

 

 

 

android listview

Adding searching functionality to Android Listview is very good habit because it allows user to search faster and get the things immediately . Lets see how it works –

Download Code

STEPS – 

1. create new project in eclipse IDE  , goto File  New Android Project . Give your desire Project Name .

2). Choose your desire activity in which you want to show your Listview , i am Using activity_main.xml .

Here is my  activiy_main.xml

<?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" >

<!-- Editext for Search -->
<EditText android:id="@+id/inputSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Search products.."
android:inputType="textVisiblePassword"/>

<!-- List View -->
<ListView
android:id="@+id/list_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

</LinearLayout>

Item_listview.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    <!-- Single ListItem -->
    
    <!-- Product Name -->
    <TextView android:id="@+id/product_name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:textSize="16dip"
        android:textStyle="bold"/>    

</LinearLayout>

3). Now open your MainActivity.java file in which you have to add array [ ] of String Type and set Listview to Adapter.

package androidarena.listviewsearch;

import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

public class MainActivity extends Activity {
	
	// List view
	private ListView lv;
	
	// Listview Adapter
	ArrayAdapter<String> adapter;
	
	// Search EditText
	EditText inputSearch;
	
	
	// ArrayList for Listview
	ArrayList<HashMap<String, String>> productList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // Listview Data
        String products[] = {"Afghanistan",
        		"Albania",
        		"Algeria",
        		"Andorra",
        		"Angola",
        		"Antigua and Barbuda",
        		"Argentina",
        		"Armenia",
        		"Australia",
        		"Austria",
        		"Azerbaijan",
        		"Bahamas",
        		"Bahrain",
        		"Bangladesh",
        		"Barbados",
        		"Belarus",
        		"Belgium",
        		"Belize",
        		"Benin",
        		"Bhutan",
        		"Bolivia",
        		"Bosnia and Herzegovina",
        		"Botswana",
        		"Brazil",
        		"Brunei",
        		"Bulgaria",
        		"Burkina Faso",
        		"Burundi",
        		"Cambodia",
        		"Cameroon",
        		"Canada",
        		"Cape Verde",
        		"Central African Republic",
        		"Chad",
        		"Chile",
        		"China",
        		"Colombi",
        		"Comoros",
        		"Congo (Brazzaville)",
        		"Congo",
        		"Costa Rica",
        		"Cote d'Ivoire",
        		"Croatia",
        		"Cuba",
        		"Cyprus",
        		"Czech Republic",
        		"Denmark",
        		"Djibouti",
        		"Dominica",
        		"Dominican Republic",
        		"East Timor (Timor Timur)",
        		"Ecuador",
        		"Egypt",
        		"El Salvador",
        		"Equatorial Guinea",
        		"Eritrea",
        		"Estonia",
        		"Ethiopia",
        		"Fiji",
        		"Finland",
        		"France",
        		"Gabon",
        		"Gambia, The",
        		"Georgia",
        		"Germany",
        		"Ghana",
        		"Greece",
        		"Grenada",
        		"Guatemala",
        		"Guinea",
        		"Guinea-Bissau",
        		"Guyana",
        		"Haiti",
        		"Honduras",
        		"Hungary",
        		"Iceland",
        		"India",
        		"Indonesia",
        		"Iran",
        		"Iraq",
        		"Ireland",
        		"Israel",
        		"Italy",
        		"Jamaica",
        		"Japan",
        		"Jordan",
        		"Kazakhstan",
        		"Kenya",
        		"Kiribati",
        		"Korea, North",
        		"Korea, South",
        		"Kuwait",
        		"Kyrgyzstan",
        		"Laos",
        		"Latvia",
        		"Lebanon",
        		"Lesotho",
        		"Liberia",
        		"Libya",
        		"Liechtenstein",
        		"Lithuania",
        		"Luxembourg",
        		"Macedonia",
        		"Madagascar",
        		"Malawi",
        		"Malaysia",
        		"Maldives",
        		"Mali",
        		"Malta",
        		"Marshall Islands",
        		"Mauritania",
        		"Mauritius",
        		"Mexico",
        		"Micronesia",
        		"Moldova",
        		"Monaco",
        		"Mongolia",
        		"Morocco",
        		"Mozambique",
        		"Myanmar",
        		"Namibia",
        		"Nauru",
        		"Nepal",
        		"Netherlands",
        		"New Zealand",
        		"Nicaragua",
        		"Niger",
        		"Nigeria",
        		"Norway",
        		"Oman",
        		"Pakistan",
        		"Palau",
        		"Panama",
        		"Papua New Guinea",
        		"Paraguay",
        		"Peru",
        		"Philippines",
        		"Poland",
        		"Portugal",
        		"Qatar",
        		"Romania",
        		"Russia",
        		"Rwanda",
        		"Saint Kitts and Nevis",
        		"Saint Lucia",
        		"Saint Vincent",
        		"Samoa",
        		"San Marino",
        		"Sao Tome and Principe",
        		"Saudi Arabia",
        		"Senegal",
        		"Serbia and Montenegro",
        		"Seychelles",
        		"Sierra Leone",
        		"Singapore",
        		"Slovakia",
        		"Slovenia",
        		"Solomon Islands",
        		"Somalia",
        		"South Africa",
        		"Spain",
        		"Sri Lanka",
        		"Sudan",
        		"Suriname",
        		"Swaziland",
        		"Sweden",
        		"Switzerland",
        		"Syria",
        		"Taiwan",
        		"Tajikistan",
        		"Tanzania",
        		"Thailand",
        		"Togo",
        		"Tonga",
        		"Trinidad and Tobago",
        		"Tunisia",
        		"Turkey",
        		"Turkmenistan",
        		"Tuvalu",
        		"Uganda",
        		"Ukraine",
        		"United Arab Emirates",
        		"United Kingdom",
        		"United States",
        		"Uruguay",
        		"Uzbekistan",
        		"Vanuatu",
        		"Vatican City",
        		"Venezuela",
        		"Vietnam",
        		"Yemen",
        		"Zambia",
        		"Zimbabwe"};
        
        lv = (ListView) findViewById(R.id.list_view);
        inputSearch = (EditText) findViewById(R.id.inputSearch);
        
        // Adding items to listview
        adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, products);
        lv.setAdapter(adapter);
        
        /**
         * Enabling Search Filter
         * */
        inputSearch.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
				// When user changed the Text
				MainActivity.this.adapter.getFilter().filter(cs);	
			}
			
			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub							
			}
		});
    }
    
}

Output –

output

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="androidarena.listviewsearch"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:icon="@drawable/logo"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="androidarena.listviewsearch.MainActivity"
            android:label="@string/title_activity_main"
            android:windowSoftInputMode="stateHidden">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Final Output –

final ouput

For more Query do comment and Post on this Tutorial . enjoy and happy Coding 🙂