Home » Android » java – How to access LayoutManager from RecyclerView.Adapter to get scrollToPosition?

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

Posted by: admin May 14, 2020 Leave a comment


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) {
        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?

How to&Answers:

Make constuctor of MyAdapter as follow.

 MyAdapter myAdapter=new MyAdapter(context,list,mLayoutManager);


Another approach

public void onAttachedToRecyclerView(RecyclerView recyclerView) {
    this.recyclerView = recyclerView;