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?
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.
Make constuctor of MyAdapter as follow.
MyAdapter myAdapter=new MyAdapter(context,list,mLayoutManager);
Another approach
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
this.recyclerView = recyclerView;
}
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