Search This Blog

Sunday, 25 March 2012

Android ListView with Section Header

ListView is most power full Widget  in android.I have mention it every time i post related to ListView.We have already learned how to create a ListView with  BaseAdapter. Now in above case if you have following problem ---
  • You want to make a song list with header to make user interface more interactive
  • There may be many more cases in which we want to give our ListView more fancy way to interact with user
For creating a List-Activtiy or ListView with section wise, we need following thing--
  • Header XML
  • Normal ListRow XML
  • Main Activity with ListView
  • Adapter class

Now  i am going to explain with code now step by step

Step 1) Create one New project

Step 2) Create XML name item1.xml inside res/layout folder.


 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_height="wrap_content"
 android:layout_width="fill_parent">
 <TextView
  android:id="@+id/text"
  android:layout_height="50dp"
  android:gravity="center_vertical"
  android:text="text"
  android:visibility="visible"
  android:layout_width="fill_parent"
  android:textColor="#FF000000"
  android:background="#FFFFFFFF" />
</LinearLayout>


Step 3) Create XML name item2.xml inside res/layout folder


 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_height="wrap_content"
 android:layout_width="fill_parent">
 <TextView
  android:id="@+id/textSeparator"
  android:layout_height="wrap_content"
  android:gravity="center"
  android:text="text"
  android:visibility="visible"
  android:layout_width="fill_parent"
  android:textColor="#FFFFFFFF"
  android:background="#000" />
</LinearLayout>


Step 4) Change your activity to List-activity.You can implement with a normal activity. For this you have to take main.xml with ListView. Paste this code inside your list-activity


package com.ahmad.list;

import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.TreeSet;

public class MultipleItemsList extends ListActivity implements OnTouchListener{

    private MyCustomAdapter mAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mAdapter = new MyCustomAdapter();
        for (int i = 1; i < 50; i++) {
            mAdapter.addItem("Sameer Blog " + i);
            if (i % 4 == 0) {
                mAdapter.addSeparatorItem("Ahmad " + i);
            }
        }
        setListAdapter(mAdapter);
    }
 //Adapter Class
 private class MyCustomAdapter extends BaseAdapter {

        private static final int TYPE_ITEM = 0;
        private static final int TYPE_SEPARATOR = 1;
        private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 1;

        private ArrayList<String> mData = new ArrayList<String>();
        private LayoutInflater mInflater;

        private TreeSet<Integer> mSeparatorsSet = new TreeSet<Integer>();

        public MyCustomAdapter() {
            mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        public void addItem(final String item) {
            mData.add(item);
            notifyDataSetChanged();
        }

        public void addSeparatorItem(final String item) {
            mData.add(item);
            // save separator position
            mSeparatorsSet.add(mData.size() - 1);
            notifyDataSetChanged();
        }

        @Override
        public int getItemViewType(int position) {
            return mSeparatorsSet.contains(position) ? TYPE_SEPARATOR : TYPE_ITEM;
        }

        @Override
        public int getViewTypeCount() {
            return TYPE_MAX_COUNT;
        }

        public int getCount() {
            return mData.size();
        }

        public String getItem(int position) {
            return mData.get(position);
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            int type = getItemViewType(position);
            System.out.println("getView " + position + " " + convertView + " type = " + type);
            if (convertView == null) {
                holder = new ViewHolder();
                switch (type) {
                    case TYPE_ITEM:
                        convertView = mInflater.inflate(R.layout.item1, null);
                        holder.textView = (TextView)convertView.findViewById(R.id.text);
                        break;
                    case TYPE_SEPARATOR:
                        convertView = mInflater.inflate(R.layout.item2, null);
                        holder.textView = (TextView)convertView.findViewById(R.id.textSeparator);
                        break;
                }
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder)convertView.getTag();
            }
            holder.textView.setText(mData.get(position));
            return convertView;
        }

    }

    public static class ViewHolder {
        public TextView textView;
    }

 public boolean onTouch(View v, MotionEvent event) {
  // TODO Auto-generated method stub
  return false;
 }
}

Screen Shot of output of this Program ---





Feel free to comment for suggestion and issue

11 comments:

  1. Its really very nice tutorial and help me a lot.
    I have one query.
    can we Fix section at top like iPhone..

    Your help is really appreciative

    ReplyDelete
    Replies
    1. I do not have any idea how its in iphone.If you want any help then you can mail me on my id with detail explanation if your problem

      Delete
  2. i got error..please check MultipleItemsList.java

    ReplyDelete
  3. salam tofeeq, i got an error with these source code, it says in getSystemService...bcause im not familiar in android programming, Could u explain please.. thanks

    ReplyDelete
    Replies
    1. Specify the error you are getting then only, i can help you

      Delete
  4. hi tofeeq....

    it's really good, but, how to use your code if my activity not extends to ListActivity ?
    it's will invoke an error like jalu said ...

    and how if ArrayList is a model/entity ?
    i mean is my list have 1 ImageView and 2 TextView how to use separator with 1 TextView?

    Thx Before

    ReplyDelete
    Replies
    1. As you talked about getSystemService, Its a part of activity, so always acess this activitycontext.getSystemService(). And for further customization change your row layout and add array in constructor to pass values

      Delete
  5. This only works for simple textviews, if you have a complex item like title, description and date, this won't work.

    ReplyDelete
  6. Yes it will not work for the requirement with changing the code. You can customizing row and Header xml and Array easily. This example just gave you the idea of ListView with Header

    ReplyDelete
  7. As you talked about getSystemService, Its a part of activity, so always acess this activitycontext.getSystemService(). And for further customization change your row layout and add array in constructor to pass values

    ReplyDelete
  8. I do not have any idea how its in iphone.If you want any help then you can mail me on my id with detail explanation if your problem

    ReplyDelete

Feedback always help in improvement. If you have any query suggestion feel free to comment and Keep visiting my blog to encourage me to blogging

Android News and source code