调用onBindViewHolder时它是如何工作的? [英] When onBindViewHolder is called and how it works?

查看:1437
本文介绍了调用onBindViewHolder时它是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是初学者,我在理解一段代码时遇到了麻烦。有人可以在这个函数唤起它时解释我是什么意思吗?

I am a beginner and I am having trouble with understanding a piece of code. Can someone please explain me when this function evoke and what is it for?

这是我的代码:

    public void onBindViewHolder(myViewHolder holder, int position) {

        RecViewHolder currentdata = data.get(position);
        holder.favChecker = currentdata.getFavChecker();
        holder.serialID = currentdata.getSerialID();
        holder.theClassName = currentdata.getTheClassName();
}


推荐答案

让我先从一个开始一点点背景(你可能已经理解了,但需要解释 onBindViewHolder())。

Let me start with just a little bit of background (which you may already understand, but it's needed to explain onBindViewHolder()).

RecyclerView 旨在显示项目的长列表(或网格)。假设您要显示100行内容。一个简单的方法是创建100个视图,每行一个并将所有视图放在一起。但这样做会很浪费,因为大多数都不在屏幕上,因为我们可以说只有10个适合屏幕。

RecyclerView is designed to display long lists (or grids) of items. Say you want to display 100 rows of something. A simple approach would be to just create 100 views, one for each row and lay all of them out. But that would be wasteful, because most of them would be off screen, because lets say only 10 of them fit on screen.

所以 RecyclerView 而只创建屏幕上的10个视图。这样,您可以获得10倍更好的速度和内存使用率。但是当您开始滚动并需要开始显示下一个视图时会发生什么?

So RecyclerView instead creates only the 10 views that are on screen. This way you get 10x better speed and memory usage. But what happens when you start scrolling and need to start showing next views?

同样,一个简单的方法是为您需要显示的每个新行创建一个新视图。但是当你到达列表末尾时,你将创建100个视图,你的内存使用量将与第一种方法相同。创建视图需要时间,因此滚动很可能不会很顺利。

Again a simple approach would be to create a new view for each new row that you need to show. But this way by the time you reach the end of the list you will have created 100 views and your memory usage would be the same as in the first approach. And creating views takes time, so your scrolling most probably wouldn't be smooth.

这就是为什么 RecyclerView 需要当您滚动并且新行出现在屏幕上时,旧行也会从屏幕上消失。而不是为每个新行创建新视图,旧视图回收,并通过将新数据绑定到它来重复使用。

This is why RecyclerView takes advantage of the fact that as you scroll and new rows come on screen also old rows disappear off screen. Instead of creating new view for each new row, an old view is recycled and reused by binding new data to it.

这恰好发生在 onBindViewHolder()。最初,您将获得新的未使用的视图持有者,您必须使用要显示的数据填充它们。但是当你滚动时,你将开始获得用于屏幕上的行的视图持有者,你必须用新数据替换他们持有的旧数据。

This happens exactly in onBindViewHolder(). Initially you will get new unused view holders and you have to fill them with data you want to display. But as you scroll you'll start getting view holders that were used for rows that went off screen and you have to replace old data that they held with new data.

这篇关于调用onBindViewHolder时它是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆