Generate Your CustomListView in Android

Posted on by By Nikhilesh, in Miscellaneous | 0

Generate Your CustomListView in Android

This tutorial will help you to generate custom listview in android. I think you know a little bit about Andorid. For this you need following classes and xml layout. I assume that you also know about registerForContextmenu.

First you need an adapter class (say MyCustomAdapter) which extends ArrayAdapter<yourCustomClass>. After extending it contains some @override method. It has getView method. In that method you have to inflate xml file otherwise your application will stop unfortunately. After inflating, find and set values to textView and imageView.


            // showing imageview according to dirTree.favouriteReport()   
	    ImageView i = (ImageView) temp.findViewById(R.id.imageView1);          
	    if(dirTree.favouriteReport() == true) {
	    	i.setVisibility(View.VISIBLE);
	    } else {
	    	i.setVisibility(View.INVISIBLE);
	    }				 	    

MyCustomAdapter.java


package com.example.mycustomlistview;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MyCustomAdapter extends ArrayAdapter<MyCustomClass> {
    List<MyCustomClass> itemlist;
    ArrayList<MyCustomClass> itemarraylist;
    LayoutInflater inflater;
    Context context;
    MyCustomClass dirTree;
    public MyCustomAdapter(Context context, List<MyCustomClass> itemlist) {
		 super(context, R.layout.mycustomlistview, itemlist);
	        this.context = context;
	        this.itemarraylist = new ArrayList<MyCustomClass>();
	        inflater = LayoutInflater.from(context);
	        this.itemlist = itemlist;		
	        itemarraylist.addAll(itemlist);
	}
    @Override
    public View getView(int position, View convertView, final ViewGroup parent) {	        		    
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View temp = convertView;
		if(temp == null) 
			temp = inflater.inflate(R.layout.mycustomlistview, parent,false);					
	    dirTree = itemlist.get(position);		
		TextView t = (TextView) temp.findViewById(R.id.textView1);
		t.setText(dirTree.getReportTitle());			
		TextView t2 = (TextView) temp.findViewById(R.id.textView2);
		t2.setText(dirTree.getPath());
		ImageView i = (ImageView) temp.findViewById(R.id.imageView1);          
	    if(dirTree.favouriteReport() == true) {
	    	i.setVisibility(View.VISIBLE);
	    } else {
	    	i.setVisibility(View.INVISIBLE);
	    }				 	    
      return temp;		
    }	       
}

This MyCustomClass.java contains getter and setter methods. Getter method is used to get value and setter method is used to set value to particular object


MyCustomClass.java
package com.example.mycustomlistview;
public class MyCustomClass {
	 private String reportTitle;
     private String path;
     private boolean favouritereport;
     public MyCustomClass(String titleString,String pathString,boolean favouritereport) {
   	  super();
   	  this.reportTitle = titleString;
   	  this.path = pathString;
   	  this.favouritereport = favouritereport;
	  }            
	 // these are getter methods
      public String getReportTitle() {
	   	  	 return reportTitle;
	  }
	  public String getPath() {
   	   	 return path;
      }
      public boolean favouriteReport() {
	     return favouritereport;
	  }
      
      // these are setters method
	  public boolean isFavouritereport() {
		 return favouritereport;
	  }
	  public void setFavouritereport(boolean favouritereport) {
		 this.favouritereport = favouritereport;
	  }
	  public void setReportTitle(String reportTitle) {
		 this.reportTitle = reportTitle;
	  }
	  public void setPath(String path) {
		this.path = path;
	}	        
}

Create your xml file for your customlist. I have created an xml which contains two textview and one imageview. ImageView indicates whether your selected item is favourite or not.


mycustomlistview.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="10dp"
    android:orientation="vertical" >
   
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="25dp"
        android:paddingBottom="3dp" 
        android:text="Book"
        android:textSize="16dp"
        android:textColor="#000000"
        android:textStyle="bold"
        />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="15dp"
        android:layout_below="@+id/textView1"
        android:text="Author"
        android:textColor="#000000" 
        android:textSize="12dp"/>

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="20dp"
        android:src="@drawable/ic_action_important" />
</RelativeLayout>

Now In your Main Class (in my case MyCustomListView.java). Follow these simple step
1) Make an ArrayList of type MyCustomClass


	ArrayList<MyCustomClass> array_list = new ArrayList<MyCustomClass>(); 

2) Then add values to array_list


	    array_list.add(new MyCustomClass("Java Black Book","Steven Holzner",false));
	    array_list.add(new MyCustomClass("Let us C","Yashwant Kanetkar",false));
	    array_list.add(new MyCustomClass("Let us C++","Yashwant Kanetkar",false));
	    array_list.add(new MyCustomClass("The Complete Reference","Herbert 
        

3) Initialize an adapter and set adapter to listview


        MyCustomAdapter myCustomAdapter;
        myCustomAdapter = new MyCustomAdapter(getApplicationContext(), array_list);        

Congratulation , you have created your custom listview. Which is static If you want to delete an item from list or mark list item as favourite you have to use registerForContextMenu(youlistview). This will call an xml file which contains two item i.e Delete and Mark as Favourite. This registerForContextMenu(yourlistview) contains two methods

Note : use myCustomAdapter.notifyDataSetChanged(); which cause refreshing of your listview.


    	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
	    super.onCreateContextMenu(menu, v, menuInfo);	    
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.contextmenu, menu);	    
	}
	@Override
	public boolean onContextItemSelected(MenuItem item) {
	    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();	    
//this will return position of your selected listitem	    
int position = info.position;
            // create an object of type MyCustomClass            
	    MyCustomClass d;
		d = array_list.get(position);
		d.favouriteReport(); // for reference what it contains
		
	    switch (item.getItemId()) {
	        case R.id.mark:	        		        		       	   		
	       	    d.setFavouritereport(true); 	    
		 	    myCustomAdapter.notifyDataSetChanged();			    	        		        	
	            return true;
	        case R.id.delete:            	
	        	
	            array_list.remove(position);       	   
	            myCustomAdapter.notifyDataSetChanged();
	            return true;	            
	        default:
	            return super.onContextItemSelected(item);
	    }
	}	

Complete java class MyCustomListView.java


MyCustomListView.java
package com.example.mycustomlistview;

import java.util.ArrayList;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class MyCustomListView extends ActionBarActivity {
	ArrayList<MyCustomClass> array_list = new ArrayList<MyCustomClass>();
	MyCustomAdapter myCustomAdapter;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_mycustomlistview);
				
		
	    array_list.add(new MyCustomClass("Java Black Book","Steven Holzner",false));
	    array_list.add(new MyCustomClass("Let us C","Yashwant Kanetkar",false));
	    array_list.add(new MyCustomClass("Let us C++","Yashwant Kanetkar",false));
	    array_list.add(new MyCustomClass("The Complete Reference","Herbert Schildt",true));
		
	    myCustomAdapter = new MyCustomAdapter(getApplicationContext(), array_list);
	    ListView listview = (ListView) findViewById(R.id.listView1);
	    listview.setAdapter(myCustomAdapter);
	    registerForContextMenu(listview);
	    
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
	    super.onCreateContextMenu(menu, v, menuInfo);	    
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.contextmenu, menu);	    
	}
	@Override
	public boolean onContextItemSelected(MenuItem item) {
	    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();	    
	    int position = info.position;
	    MyCustomClass d;
		d = array_list.get(position);
		d.favouriteReport();
		
	    switch (item.getItemId()) {
	        case R.id.mark:	        		        		       	   			
	       	    d.setFavouritereport(true); 	    
			    myCustomAdapter.notifyDataSetChanged();			    	        		        	
	            return true;
	        case R.id.delete:            	
	        	
	            array_list.remove(position);       	   
	            myCustomAdapter.notifyDataSetChanged();
	            return true;	            
	        default:
	            return super.onContextItemSelected(item);
	    }
	}	
}

Screenshot

When activity started

When Activity Started

When registerForContextMenu is invoked

Display Context

When item is deleted.

After Delete

When item is marked as Favourite.

When Mark as Faourite

logo

Best Open Source Business Intelligence Software Helical Insight is Here

logo

A Business Intelligence Framework

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments