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

I customized RecyclerView by adding separate layouts for the header and footer. I created constants to define the properties of the header, footer, and list item in the adapter class. I also created a ViewHolder template and assigned layouts to be shown based on the type of view. I fixed the header at the zero position and the footer at the last position of the array by overriding the getItemViewType method.

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

My goal is to click the footer and scrollToPosition 0 or 1 (0 = Title, 1 = element of the first element).

This is the definition of MyAdapter:

 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 cannot access the LayoutManager from the Adapter class. Any ideas what I can do?

+5
source share
2 answers

Make constuctor MyAdapter as follows.

  MyAdapter myAdapter=new MyAdapter(context,list,mLayoutManager); 
+3
source

Another approach

 @Override public void onAttachedToRecyclerView(RecyclerView recyclerView) { super.onAttachedToRecyclerView(recyclerView); this.recyclerView = recyclerView; } 
+4
source

Source: https://habr.com/ru/post/1264298/


All Articles