I want that my first element in recycler view have offset by start list.
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.
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"/>
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With