RecyclerView With Multiple Layouts

前端 未结 3 1268
刺人心
刺人心 2021-01-16 04:58

I am using RecyclerView to display text in CardView but I want to add a Header TextView at the top of the RecyclerView that looks like this:

3条回答
  •  误落风尘
    2021-01-16 05:24

    You need to make three changes:

    1. Implement getItemViewType() on your RecyclerView.Adapter, to return a unique integer for each view type needed by your app, based on the supplied position. So, you would return one value for your header (presumably a position of 0) and another value for everything else.

    2. Pay attention to the viewType parameter passed into onCreateViewHolder(), and create an appropriate RecyclerView.ViewHolder as needed. This in turn probably means that you should have different ViewHolder classes for your header and detail rows.

    3. In onBindViewHolder(), apply binding logic based upon the type of the ViewHolder that you get, so you bind the appropriate data into the ViewHolder. You can use instanceof, or have the ViewHolder classes implement a common interface, or whatever to make this work.

    This sample app demonstrates a RecyclerView with section headers that implements the above steps.

提交回复
热议问题