33

Is it possible to use categories or some sort of headers with a GridView in Android?

I put together a quick illustration of what I was thinking about:

enter image description here

Thanks a lot.

Michell Bak
  • 13,182
  • 11
  • 64
  • 121

4 Answers4

15

You can use Stickygridheaders library directly or as a model to create your own widget.

Andrei B.
  • 1,000
  • 9
  • 14
3

probably this code will help you. This is SectionedGridRecyclerViewAdapter, result looks like this:

enter image description here

girlOnSledge
  • 402
  • 1
  • 5
  • 8
  • can you advice how to add click listener to this adapter? – AEMLoviji Jan 22 '16 at 14:03
  • 1
    @AEMLoviji On SimpleAdapter class, on onBindViewHolder method add this: holder.itemView.setOnClickListener – dilettante Jan 16 '19 at 17:54
  • Thank you @dilettante for your answer. Currently I am not developing mobile apps any more. It was 3 years ago I asked this question. It seems way you have provided will work correctly. – AEMLoviji Jan 17 '19 at 07:26
2


You can modify the usual listview adapter to return a grids at each row see here

public GenericModelAdapter(Context context, int textViewResourceId, List<Map<String, List<Object>>> items, Map<String, String> sectionHeaderTitles, int numberOfCols, View.OnClickListener mItemClickListener){
    super(context, textViewResourceId, items);
    this.items = items;
    this.numberOfCols = numberOfCols;
    layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    this.mItemClickListener = mItemClickListener;
    this.sectionHeaderTitles = sectionHeaderTitles;
}

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

    if(isHeaderPosition(position)){
        convertView = layoutInflater.inflate(R.layout.grid_header_view, null);

        TextView headerText = (TextView)convertView.findViewById(R.id.headerText);
        String section = getItemTypeAtPosition(position);
        headerText.setText(getHeaderForSection(section));
        return convertView;
    }else{
        LinearLayout row = (LinearLayout)layoutInflater.inflate(R.layout.row_item, null);
        Map<String, List<Object>> map = getItem(position);
        List<Object> list = map.get(getItemTypeAtPosition(position));

        for (int i = 0; i < numberOfCols; i++){
            FrameLayout grid = (FrameLayout)layoutInflater.inflate(R.layout.grid_item, row, false);
            ImageView imageView;
            if (i < list.size()){
                GenericModel model = (GenericModel)list.get(i);
                if (grid != null){
                    imageView = (ImageView)grid.findViewWithTag("image");
                    imageView.setBackgroundResource(model.getImageResource());

                    TextView textView = (TextView)grid.findViewWithTag("subHeader");
                    textView.setText(model.getHeader());

                    grid.setTag(R.id.row, position);
                    grid.setTag(R.id.col, i);
                    grid.setOnClickListener(mItemClickListener);
                }
            }else{
                if (grid != null){
                    grid.setVisibility(View.INVISIBLE);
                    grid.setOnClickListener(null);
                }
            }
            row.addView(grid);
        }
        return row;
    }
}

@Override
public int getCount() {
    int totalItems = 0;
    for (Map<String, List<Object>> map : items){
        Set<String> set = map.keySet();
        for(String key : set){
            //calculate the number of rows each set homogeneous grid would occupy
            List<Object> l = map.get(key);
            int rows = l.size() % numberOfCols == 0 ? l.size() / numberOfCols : (l.size() / numberOfCols) + 1;

            // insert the header position
            if (rows > 0){
                headerPositions.add(String.valueOf(totalItems));
                offsetForItemTypeMap.put(key, totalItems);

                itemTypePositionsMap.put(key, totalItems + "," + (totalItems + rows) );
                totalItems += 1; // header view takes up one position
            }
            totalItems+= rows;
        }
    }
    return totalItems;
}

@Override
public Map<String, List<Object>> getItem(int position) {
    if (!isHeaderPosition(position)){
        String itemType = getItemTypeAtPosition(position);
        List<Object> list = null;
        for (Map<String, List<Object>> map : items) {
            if (map.containsKey(itemType)){
                list = map.get(itemType);
                break;
            }
        }
        if (list != null){
            int offset = position - getOffsetForItemType(itemType);
            //remove header position
            offset -= 1;
            int low = offset * numberOfCols;
            int high = low + numberOfCols  < list.size() ? (low + numberOfCols) : list.size();
            List<Object> subList = list.subList(low, high);
            Map<String, List<Object>> subListMap = new HashMap<String, List<Object>>();
            subListMap.put(itemType, subList);
            return subListMap;
        }
    }
    return null;
}

public String getItemTypeAtPosition(int position){
    String itemType = "Unknown";
    Set<String> set = itemTypePositionsMap.keySet();

    for(String key : set){
        String[] bounds = itemTypePositionsMap.get(key).split(",");
        int lowerBound = Integer.valueOf(bounds[0]);
        int upperBoundary = Integer.valueOf(bounds[1]);
        if (position >= lowerBound && position <= upperBoundary){
            itemType = key;
            break;
        }
    }
    return itemType;
}

public int getOffsetForItemType(String itemType){
    return offsetForItemTypeMap.get(itemType);
}

public boolean isHeaderPosition(int position){
    return headerPositions.contains(String.valueOf(position));
}

private String getHeaderForSection(String section){
    if (sectionHeaderTitles != null){
        return sectionHeaderTitles.get(section);
    }else{
        return section;
    }
}

GridView with sample fruit categories

korosmatick
  • 579
  • 4
  • 8
2

I think You can do it but you have to implement Jeff Shrkey's SeparatedListAdapter

There isn’t an easy way of creating these separated lists, so I’ve put together SeparatedListAdapter which does it quickly. To summarize, we’re creating a new BaseAdapter that can contain several other Adapters, each with their own section headers.

ingsaurabh
  • 15,249
  • 7
  • 52
  • 81
  • 7
    How does this have any votes? The SeperatedListAdapter only seems to apply to ListViews... – greg7gkb Nov 13 '13 at 00:18
  • @ingsaurabhi will this work for gridview too with this library https://github.com/TonicArtos/StickyGridHeaders/ – Erum Aug 24 '15 at 12:18