RecyclerView with start offset

Никита Куликов picture Никита Куликов · Aug 2, 2016 · Viewed 7.4k times · Source

I want that my first element in recycler view have offset by start list. first position when scroll down

I try use

void onCreate(Bundle savedInstanceState){
...
    linearLayoutManager.scrollToPositionWithOffset
...
}

But it not work. I undestand that i can use empty view how zero element in list, but it not perfect solution.

Answer

JCDecary picture JCDecary · Aug 2, 2016

First solution:

public class Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    public static final int VIEW_HEADER = 1, VIEW_INFO = 2;
    private Context context;

    public Adapter(Context context) {
        this.context = context;
    }

    @Override
    public int getItemViewType(int position) {
        if(position == 0) return VIEW_HEADER;
        return VIEW_INFO;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType){
            case VIEW_HEADER:
                return new HeaderViewHolder(LayoutInflater.from(context).inflate(your view));
            case VIEW_INFO:
                return new InfoViewHolder(LayoutInflater.from(context).inflate(your view));
        }
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if(holder instanceof HeaderViewHolder){

        }else if (holder instanceof InfoViewHolder){

        }
    }

    @Override
    public int getItemCount() {
        return your items count + 1; // add the header
    }

    public static class HeaderViewHolder extends RecyclerView.ViewHolder{

        public HeaderViewHolder(View itemView) {
            super(itemView);
        }
    }

    public static class InfoViewHolder extends RecyclerView.ViewHolder{

        public InfoViewHolder(View itemView) {
            super(itemView);
        }
    }
}

second solution:add paddingTop to your recyclerview, and add clipToPadding false.

<androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingTop="100dp"
        android:clipToPadding="false"/>