javaandroidlistandroid-recyclerviewlist-separator

How to add separator at particular position inside recyclerview?


I have a list of taskLists. To show the list I have used recyclerview. I have 1st 3 items as today , tomorrow and later in my list. I want to add one separator after 1st 3 items in recycler view. How can I do this?

Adapter :

    public class ListAdapter extends RecyclerView.Adapter<ListAdapter.ItemViewHolder>{

    ArrayList<ListData> item;
    public static final int TYPE1=1;
    Context conext;


  public   ListAdapter(Context context, ArrayList<ListData> item) {
        this.conext=context;
        this.item=item;

    }
    public interface OnItemClickListener {
        void onItemClick(ListData listData);
    }
    @Override
    public int getItemCount() {
        return item.size();

    }
    public void remove(int position) {
        item.remove(position);
        notifyItemRemoved(position);
    }

   // @Override
   // public int getItemViewType(int position) {
       // return item.get(position).getExpenseType();// Assume that this return 1 0r 2
  //  }

    @Override
    public void onBindViewHolder(ItemViewHolder itemViewHolder,final int i) {

        itemViewHolder.listName.setText(item.get(i).getTitle());

    }

    @Override
    public ItemViewHolder onCreateViewHolder(ViewGroup viewGroup,int viewType) {

        View itemView = LayoutInflater.
                from(viewGroup.getContext()).
                inflate(R.layout.list_layout, viewGroup, false);
        return new ItemViewHolder(itemView,viewType);

    }


    public static class ItemViewHolder extends RecyclerView.ViewHolder {

        TextView listName;


        ItemViewHolder(View itemView, int viewType) {
            super(itemView);

            listName  = (TextView)itemView.findViewById(R.id.listData);

        }
    }
    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
    }

}

Can anyone help with this how can I put separator after 3 items in list? Thank you..


Solution

  • One solution is define 2 types of RecyclerView rows (one for normal row and one for separator) Another solution is you should a Separator View in the bottom of your custom RecycleView row xml

    <View
        android:id="@+id/separatorView"
        android:layout_width="match_parent"
        android:layout_height="3dp"
        android:visible="gone"
        android:background="@android:color/darker_gray"/>
    

    Then in bindViewHolder of your RecyclerView.Adapter, hide the separator in normal row and visible it in separator row

     @Override
        public void bindViewHolder(ViewHolder holder, int position) {
            if(position == separatorPosition){
               holder.separatorView.visible = View.VISIBLE;
            }else{
               holder.separatorView.visible = View.GONE;
            }
        }
    

    Hope this help