How to add divider items to ListView


SDK Version: 
M3

Today I'm going to show an easy way to add divider items to your ListView.
First off, you need your own ListView Adapter which extends SimpleAdapter. If you don't know how to create a new class for your own SimpleAdapter, please go and visit: http://developer.android.com/resources/samples/ApiDemos/src/com/example/...

Ok, so here's how it looks like:

  1. public class SpecialAdapter extends SimpleAdapter {
  2.         private LayoutInflater mInflater;
  3.         private List<HashMap<String, String>> items;
  4.  
  5.         public SpecialAdapter(Context context, List<HashMap<String, String>> items, int resource, String[] from, int[] to) {
  6.                 super(context, items, resource, from, to);
  7.                 // Cache the LayoutInflate to avoid asking for a new one each time.
  8.         this.items = items;
  9.         }
  10.  
  11.          @Override
  12.      public boolean areAllItemsEnabled() {
  13.          return false;
  14.      }
  15.  
  16.      @Override
  17.      public boolean isEnabled(int position) {
  18.          boolean enabled = false;
  19.          if(items.size() > position){
  20.                  enabled = !items.get(position).get("name").startsWith("-");
  21.          }
  22.          
  23.          return enabled;
  24.      }

What we are looking for is the overriden "areAllItemsEnabled()" and "isEnabled" methods. If the item's name starts with "-", then it will be a divider item, which should not be clickable.
If you are more advanced, you can use a custom layout for your divider item as well, here's how to do it:

  1. public View getView(int position, View convertView, ViewGroup parent) {
  2.  
  3.         // Handle dividers
  4.         if(items.get(position).get("name").startsWith("-")){
  5.                 View divider = mInflater.inflate(R.layout.progressbar, null);
  6.                 return divider;
  7.         }
  8.        ...
  9.        ...

Same condition, if the item's name start with "-" it will use the layout: R.layout.progressbar, instead of your default list item layout.