list view with section header

ListView With section header in android example

ListView With section header in android example

We already know about ListView in android and also know about expandable listview in android.

In ExpandableListView show child view by expanding the groups view and also collapsed the child by clicking on the group view in list but Section header list view a single level view with group header, under group header the child view will be shown.

Check Source Code

ListSectionActivity.java


package com.androidfromhome.listviewsection;

import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
import com.androidfromhome.util.adapter.AndroidListAdapter;
import com.androidfromhome.util.adapter.ListSeparateAdapter;
import com.androidfromhome.util.collection.DataCollection;

public class ListSectionActivity extends Activity implements OnItemClickListener {

    private AndroidListAdapter list_adapter;
    private ListView lv_android;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_section);
        
        
        
        DataCollection.data_arr=new ArrayList<DataCollection>();
        DataCollection.data_arr.add(new DataCollection("Butterfly", "Insect", R.drawable.butterfly));
        DataCollection.data_arr.add(new DataCollection("Green Scenery", "Natural", R.drawable.green_scenery));
        DataCollection.data_arr.add(new DataCollection("Leaf", "Natural", R.drawable.leaf));
        DataCollection.data_arr.add(new DataCollection("One Rose", "Natural", R.drawable.one_rose));
        DataCollection.data_arr.add(new DataCollection("Open Sky", "Environment", R.drawable.sky));
        
        
        
        lv_android=(ListView)findViewById(R.id.lv_android);
        
        list_adapter=new AndroidListAdapter(ListSectionActivity.this, R.layout.list_item,DataCollection.data_arr);
        
        
        ListSeparateAdapter<DataCollection> listsectionAdapter = new ListSeparateAdapter<DataCollection>(ListSectionActivity.this,
                list_adapter, R.layout.enroll_section_list, R.id.tv_section);

          lv_android.setAdapter(listsectionAdapter);
          lv_android.setOnItemClickListener(this);
              
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        // TODO Auto-generated method stub
        
    DataCollection data_obj=(DataCollection) parent.getAdapter().getItem(position);
    if (data_obj!=null) {
    
        Toast.makeText(ListSectionActivity.this, "You have Selected "+data_obj.name, Toast.LENGTH_LONG).show();
            
    }
       
        
    }
  
}

 


 

 

AndroidListAdapter.java


 

package com.androidfromhome.util.adapter;

import java.util.ArrayList;
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;
import com.androidfromhome.listviewsection.R;
import com.androidfromhome.util.collection.DataCollection;

public class AndroidListAdapter extends ArrayAdapter<DataCollection>{
    
    private final Context context;
    private final ArrayList<DataCollection> values;
    private ViewHolder viewHolder;
    private final int resourceId;

    public AndroidListAdapter(Context context, int resourceId,ArrayList<DataCollection> values) {
        super(context, resourceId, values);
        // TODO Auto-generated constructor stub
        
        this.context = context;
        this.values = values;
        this.resourceId = resourceId;
    }
    
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(resourceId, parent, false);
            
                
            viewHolder = new ViewHolder();
            viewHolder.tv_title = (TextView) convertView.findViewById(R.id.tv_title);
            viewHolder.iv_image = (ImageView) convertView.findViewById(R.id.iv_image);
            
            
                convertView.setTag(viewHolder);
            
            
        }else
        {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        DataCollection list_obj=values.get(position);
        viewHolder.tv_title.setText(list_obj.name);
        viewHolder.iv_image.setImageResource(list_obj.image);
            
        return convertView;
    }
    
     
    public class ViewHolder {

         TextView tv_msg;
         ImageView iv_image;
         TextView tv_title;

    }

}

 


 

 

ListSeparateAdapter.java


 

package com.androidfromhome.util.adapter;

import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.androidfromhome.util.collection.DataCollection;

public class ListSeparateAdapter<T> extends BaseAdapter {
 
    private Context ctx;
    private BaseAdapter headerBaseAdapter;
    private int headerLayout;
    private int headerTextView;
    private HashMap<String, Integer> hashMap;
    private static final int INDEX_SECTION_HEADER = 0;
      
    
    public ListSeparateAdapter(Context ctx, BaseAdapter headerBaseAdapter,
            int headerLayout, int headerTextView) {
        if(ctx == null) {
            throw new IllegalArgumentException("context should not be null.");
        } else if(headerBaseAdapter == null) {
            throw new IllegalArgumentException("adapter should not be null.");
        }  else if(!isTypeTextView(ctx, headerLayout, headerTextView)) {
            throw new IllegalArgumentException("section Title should not match type.");
        }

        this.ctx = ctx;
        this.headerBaseAdapter = headerBaseAdapter;
        this.headerLayout = headerLayout;
        this.headerTextView = headerTextView;
       this.hashMap = new HashMap<String, Integer>();

        getSection();
        
        
    }

    private boolean isTypeTextView(Context context, int layoutId, int textViewId) {
        View inflatedView = View.inflate(context, layoutId, null);
        View foundView = inflatedView.findViewById(textViewId);

        return foundView instanceof TextView;
    }

    @Override
    public int getCount() {
        return headerBaseAdapter.getCount() + getSectionLength();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        SectionHolder sectionHolder = null;

        switch (getItemViewType(position)) {
        case INDEX_SECTION_HEADER:
            if(view == null) {
                view = View.inflate(ctx, headerLayout, null);

                sectionHolder = new SectionHolder();
                sectionHolder.textview = (TextView) view.findViewById(headerTextView);

                view.setTag(sectionHolder);
            } else {
                sectionHolder = (SectionHolder) view.getTag();
            }
            break;

        default:
            view = headerBaseAdapter.getView(getPosition(position),
                    convertView, parent);
            break;
        }

        if(sectionHolder != null) {
            String sectionName = getTitle(position);
            sectionHolder.textview.setText(sectionName);
        }

        return view;
    }

    @Override
    public boolean areAllItemsEnabled() {
        return headerBaseAdapter.areAllItemsEnabled() ?
                hashMap.size() == 0 : false;
    }

    @Override
    public int getItemViewType(int position) {
        int positionInCustomAdapter = getPosition(position);
        return hashMap.values().contains(position) ?
                INDEX_SECTION_HEADER :
                    headerBaseAdapter.getItemViewType(positionInCustomAdapter) + 1;
    }

    @Override
    public int getViewTypeCount() {
        return headerBaseAdapter.getViewTypeCount() + 1;
    }

    @Override
    public boolean isEnabled(int position) {
        return hashMap.values().contains(position) ?
                false : headerBaseAdapter.isEnabled(getPosition(position));
    }

    @Override
    public Object getItem(int position) {
        return headerBaseAdapter.getItem(getPosition(position));
    }

    @Override
    public long getItemId(int position) {
        return headerBaseAdapter.getItemId(getPosition(position));
    }

    @Override
    public void notifyDataSetChanged() {
        headerBaseAdapter.notifyDataSetChanged();
        getSection();
        super.notifyDataSetChanged();
    }

    
    
    public int getPosition(int position) {
        int pos = 0;

        Set<Entry<String, Integer>> entrySet = hashMap.entrySet();
        for(Entry<String, Integer> entry : entrySet) {
            if(entry.getValue() < position) {
                pos++;
            }
        }

        return position - pos;
    }

    static class SectionHolder {
        public TextView textview;
    }

    private void getSection() {
        int len = headerBaseAdapter.getCount();
        int nSections = 0;
        hashMap.clear();

        for(int i=0; i<len; i++) {
            
                
            DataCollection obj=(DataCollection) headerBaseAdapter.getItem(i);
            System.out.println(""+obj.type);
            String sectionName= obj.type;
            
            
            if(!hashMap.containsKey(sectionName)) {
                hashMap.put(sectionName, i + nSections);
                nSections ++;
            }
        }

      }

    private int getSectionLength() {
        return hashMap.size();
    }

    private String getTitle(int position) {
        String title = null;

        Set<Entry<String, Integer>> entrySet = hashMap.entrySet();
        for(Entry<String, Integer> entry : entrySet) {
            if(entry.getValue() == position) {
                title = entry.getKey();
                break;
            }
        }
        return title;
    }

}

 


 

 

DataCollection.java


 

package com.androidfromhome.util.collection;

import java.util.ArrayList;

public class DataCollection {
    public String name="";
    public int image=0;
    public String type="";
    
    public static ArrayList<DataCollection> data_arr=null;
    public DataCollection(String name,String type,int image){
        
        this.image=image;
        this.name=name;
        this.type=type;
    }

}

 


 

Now xml layout code

 

activity_list_section.xml


 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.androidfromhome.listview.ListViewActivity" >
    <LinearLayout
        android:id="@+id/LinearLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#A758AB"
        android:gravity="center"
        android:orientation="vertical"
        android:padding="15dp" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="2dp"
            android:text="Android From Home"
            android:textColor="#ffffff"
            android:textSize="22dp"
            android:textStyle="bold" />
    </LinearLayout>

    <ListView
        android:id="@+id/lv_android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>

 


 

 

enroll_section_list.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="wrap_content"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="2dp" >

    <TextView
        android:id="@+id/tv_section"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/bg_round_section_header"
        android:padding="8dp"
        android:text="TextView"
        android:textColor="#ffffff"
        android:textStyle="bold" />

</LinearLayout>

 


 

 

list_item.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="wrap_content"
    android:layout_gravity="center"
    android:background="#ffffff"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#ffffff"
        android:gravity="center"
        android:padding="6dp" >

        <FrameLayout
            android:layout_width="62dp"
            android:layout_height="62dp"
            android:layout_margin="2dp" >

            <ImageView
                android:id="@+id/iv_image"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:padding="3dp" />

        </FrameLayout>

        <TextView
            android:id="@+id/tv_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:padding="2dp"
            android:text="TextView"
            android:textColor="#000000"
            android:textSize="16dp"
            android:textStyle="bold" />

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:src="@drawable/arrow_list" />

    </LinearLayout>

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:background="#dfdfdf" />

</LinearLayout>


 

 

 

Download Full Source Code

 

Related Post:-

Sqlite database example in android

GridView example in android with Custom layout

how to get the call log details in android

How Retrieve contact list in android

Leave a Reply

Your email address will not be published. Required fields are marked *

Get Widget