简体   繁体   中英

General question about RecycleView.Adapter

I have a very general question about Adapters. I have code like this:

class DailySumsAdapter(private val dailySumList : List<Pair<String, Double>>, private val context : Context) : RecyclerView.Adapter<DailySumHolder>()
{
   ....
}

The list of Pairs is what I use to populate the fields of the ViewHolders. Do I have to feed a List object to the DailySumsAdapter constructor or can adapters work with other data types? I ask because I notice that onBindViewHolder() method uses "position" argument when accessing data:

override fun onBindViewHolder(holder: DailySumHolder, position: Int) { ....}

Do I have to feed a List object to the DailySumsAdapter constructor or can adapters work > with other data types

yes you have to pass this object. the adapter uses generics to ensure a specific data type is passed.

I ask because I notice that onBindViewHolder() method uses "position" argument when accessing data

The data held by the adapter is of type collection so the position is only used to access the data at a specific location in the collection. Take the position as the id of that row in the list.

An adapter is a bridge between your data source and whatever's displaying it (in this case, a "view holder" in a RecyclerView ). Your data source can be whatever you like - but generally it's going to be some kind of ordered list/sequence of stuff, because that's how it's being displayed.

With a RecyclerView.Adapter you really only have three things to worry about:

  • onCreateViewHolder aka "inflate a layout for displaying stuff"
  • onBindViewHolder aka "put stuff in the layout, displaying the item at position X "
  • getItemCount aka "how many things are in the list"

( position X is the slightly tricky part, because you might be displaying a subset of your actual source data, like if it's filtered because of a search. So in that case, you might need to translate position X in the displayed list to item Y in your source data)

The actual RecyclerView.ViewHolder (which is the generic type of your adapter) you implement can have whatever in it - really you just need to pass the inflated layout to the superclass, that's the only requirement. You'll mostly just be looking up the views for displaying things, so you can update them in onBindViewHolder .

So nah, you don't have to use a List at all, but it's common. Pass whatever you like into the adapter constructor, your code is the only thing that's using it! That's what an adapter's for, translating your stuff into something displayable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM