Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RecyclerView with start offset

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.

like image 357
Nikita Kulikov Avatar asked Aug 02 '16 13:08

Nikita Kulikov


2 Answers

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"/>
like image 160
JCDecary Avatar answered Sep 25 '22 14:09

JCDecary


I found a solution and it works great. First you need to get your recyclerviews last offset value by;

int offset = recyclerView.computeVerticalScrollOffset();

Or you can assign your offset value. Then after you set your adapter, you can set your offset like below.

recyclerView.setAdapter(Adapter.this);
LinearLayoutManager llm = (LinearLayoutManager) 
recyclerView.getLayoutManager();
llm.scrollToPositionWithOffset(0,-1*offset);

Its mean; llm scrolling position to 0(start) and then goes down to offset. I hope it helps!

like image 31
Burak Avatar answered Sep 23 '22 14:09

Burak