Search code examples
androidandroid-recyclerviewgrid-layout

Recyclerview with GridLayout. Add a divider only if date of next item differ


I have a RecyclerView with a GridLayout. My data is a List of ordered objects by date. I need to add a divider if next item has different date that current one. Here is my class:

public class ImageContentFragment extends Fragment  {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    recyclerView = (RecyclerView) mainView.findViewById(R.id.rc_recycler_view);
    adapter = new ContentAdapter(recyclerView.getContext());
    recyclerView.setAdapter(adapter);
    recyclerView.setHasFixedSize(true);
    int tilePadding = getResources().getDimensionPixelSize(R.dimen.tile_padding);
    recyclerView.setPadding(tilePadding, tilePadding, tilePadding, tilePadding);
    recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), sPrefs.getInt(GRID_COL_KEY, GRID_SPAN_COUNT)));
    return mainView;
}

public class ContentAdapter extends RecyclerView.Adapter<ContentAdapter.MyViewHolder> {

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public ImageView picture;
        public TextView name;
        public boolean selected = false;
        public MyViewHolder(View view) {
            super(view);
            picture = (ImageView) itemView.findViewById(R.id.tile_picture);
            name = (TextView) itemView.findViewById(R.id.tile_title);
        }
    }

    public ContentAdapter(Context context) {
        mUlrPictures = getImageUrlForFolder(mediaStorageDir);
    }

    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_image, parent, false);
        GridLayoutManager.LayoutParams lp = (GridLayoutManager.LayoutParams) v.getLayoutParams();
        lp.height = sPrefs.getInt(ICON_SIZE_KEY, ITEM_HEIGHT_MEDIUM);
        v.setLayoutParams(lp);
        return new MyViewHolder(v);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
            String imUrl = mUlrPictures.get(position % mUlrPictures.size()).getUrl();
            holder.name.setText(mUlrPictures.get(position % mUlrPictures.size()).getUrl());
            holder.selected = mUlrPictures.get(position % mUlrPictures.size()).getSelected();
        }
    }

    @Override
    public int getItemCount() {
        return mUlrPictures.size();
    }

}

}

What is the best way to do that? It also would be great to add a TextView with divider.


Solution

  • Add a view in item_image.xml file with height 2dp & width fill_parent, it works as a divider, assign id as well.

    onBindViewHolder method write one logic to check the dates based on the position, if true then make it visible the divider view, if not make the divider View.gone

    Hope this will help you