androidgridview

Inserting a Gridview Row after 10 items


I have no idea how to achieve this. I want to insert a row after 10th position of item in GridView. I have no idea from where to I start this. I want to do like this

Thanks and please give some advice.


Solution

  • Step 1: Define two layout item one for column and other one for row

    Step 2: Create recycler view adapter , and override below methods

    @Override
    public int getItemViewType(int position) {
        int viewType;
        if ((position + 1) % 10 == 0) {
            viewType = VIEW_TYPE_ROW;
        } else {
            viewType = VIEW_TYPE_COLUMN;
        }
        return viewType;
    }
    
    
    @Override
    public long getItemId(int position) {
        /**
         * Optimization of notifyDataSetChanged
         * Look at documentation for setHasStableIds(true) and getItemId(int position)
         */
        return STABLE_ID + position;
    }
    
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case VIEW_TYPE_COLUMN:
                 // inflate column layout and view holder
                 break;
    
            case VIEW_TYPE_ROW:
                 // inflate row layout and view holder
                 break;
        }
    }
    
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        switch (getItemViewType(position)) {
            case VIEW_TYPE_COLUMN:
                 break;
    
            case VIEW_TYPE_ROW:
                 break;
        }
    }
            
            
    

    While initializing adapter do like below

        final GridLayoutManager layoutManager = new GridLayoutManager(getActivity().getApplicationContext(), 2);
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                switch (themeAdapter.getItemViewType(position)) {
                    case ThemeAdapter.VIEW_TYPE_COLUMN:
                        return 1;
                    case ThemeAdapter.VIEW_TYPE_ROW:
                        return layoutManager.getSpanCount();
                    default:
                        return layoutManager.getSpanCount();
                }
            }
        });
    

    Here themeAdapter is your RecyclerView adapter.