Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access LayoutManager from RecyclerView.Adapter to get scrollToPosition?

I customized RecyclerView by adding separate layouts for header and footer. I created constants to determine the property of header, footer and list item in the adapter class. I also created a ViewHolder pattern and assign the layouts to be shown based on the view type. I fixed the header at zeroth position and footer at last position of the array by override getItemViewType method.

I want to make the footer element clickable, so I assign a setOnClickListener(new View.OnClickListener()) and overwrote onClick(view: View)

My goal is to click on the footer and scrollToPosition 0 or 1 (0 = Header, 1 = first item element).

That's MyAdapter definition:

class MyAdapter(context: Context, data: Array[String]) extends RecyclerView.Adapter[RecyclerView.ViewHolder]

...

override def onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int): Unit = holder match {
  ...
  case holder:FooterViewHolder =>
    holder.backToTop.setOnClickListener(new View.OnClickListener() {
      override def onClick (view: View) {
        backToTop(???)
        Toast.makeText (context, "Clicked Footer", Toast.LENGTH_SHORT).show()
      }
    })
  ...
}
...

I read I just need to do this: recyclerView.getLayoutManager().scrollToPosition(position)

Unfortunately I can't access the LayoutManager from my Adapter class. Any ideas what I can do?

like image 630
user3350744 Avatar asked Feb 16 '17 12:02

user3350744


People also ask

What is LayoutManager in RecyclerView?

A LayoutManager is responsible for measuring and positioning item views within a RecyclerView as well as determining the policy for when to recycle item views that are no longer visible to the user.


2 Answers

Make constuctor of MyAdapter as follow.

 MyAdapter myAdapter=new MyAdapter(context,list,mLayoutManager);
like image 25
Rahul Giradkar Avatar answered Sep 25 '22 15:09

Rahul Giradkar


Another approach

@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
    super.onAttachedToRecyclerView(recyclerView);
    this.recyclerView = recyclerView;
}
like image 86
Kairat Doshekenov Avatar answered Sep 23 '22 15:09

Kairat Doshekenov