Getting RecyclerView Height From OnBindViewHolder

Nathan Sokalski 4,116 Reputation points
2021-05-01T20:40:11.887+00:00

In the OnBindViewHolder method of my Adapter, I need to get the height of the associated RecyclerView. Is there a way to get a reference to the associated RecyclerView? Thanks.

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,254 questions
0 comments No comments
{count} votes

Accepted answer
  1. JarvanZhang 23,931 Reputation points
    2021-05-03T07:36:40.177+00:00

    Hello,​

    Welcome to our Microsoft Q&A platform!

    Is there a way to get a reference to the associated RecyclerView?

    Try to create a 'RecyclerView' property in the custom Adapter class and pass the recyclerView instance in Activity class.

    Check the code:

       public class MainActivity : AppCompatActivity  
       {  
           RecyclerView mRecyclerView;  
           RecyclerView.LayoutManager mLayoutManager;  
           List<model> list;  
           CustomAdapter myadapter;  
           protected override void OnCreate(Bundle savedInstanceState)  
           {  
               base.OnCreate(savedInstanceState);  
               // Set our view from the "main" layout resource  
               SetContentView(Resource.Layout.main_layout);  
         
               mRecyclerView = FindViewById<RecyclerView>(Resource.Id.recycleview);  
               mLayoutManager = new LinearLayoutManager(this);  
               mRecyclerView.SetLayoutManager(mLayoutManager);  
         
               list = new List<model>();  
               //add the data  
         
               myadapter = new CustomAdapter(list, mRecyclerView);  
               mRecyclerView.SetAdapter(myadapter);  
           }  
       }  
         
       public class CustomAdapter : RecyclerView.Adapter  
       {  
           private List<model> list;  
           RecyclerView recyclerView;  
           public CustomAdapter(List<model> list, RecyclerView recyclerView)  
           {  
               this.list = list;  
               this.recyclerView = recyclerView;  
           }  
           ...  
           public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)  
           {  
               View itemView = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.itemLayout, parent, false);  
               CustomViewHolder viewHolder = new CustomViewHolder(itemView);  
         
               //you could access the recyclerView here  
         
               return viewHolder;  
           }  
       }  
    

    Best Regards,

    Jarvan Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful