切换按钮在使用 mysqlite 数据库在 RecyclerView 中滚动时更改其状态

Mak*_*aya 0 android android-togglebutton android-recyclerview

这是我的代码

@Override
public void onBindViewHolder(final RecyclerViewHolder holder, int position) {
final Songs songs = arrayList.get(position);

holder.favorite.setChecked(songs.getFavorite()); // this line makes me confusing.

   holder.favorite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
         int r =  db.update_favorite(b,songs.getTitle(),songs.getArtist());

            compoundButton.setChecked(b);
        }
    });

}
Run Code Online (Sandbox Code Playgroud)

这里的问题是我是否包含此代码

holder.favorite.setChecked(songs.getFavorite());

onBindViewHolder,当我更改切换按钮的状态并向下滚动然后向上滚动时,切换按钮的状态将自身更改为原始状态。澄清一下,当切换按钮状态从 false 变为 true 并且用户向下和向上滚动时,切换按钮会自动变为原始状态,即为 false。

即使用户向下滚动,如何使切换按钮保持状态变化?请帮我。

Ben*_* P. 5

这是我的猜测:CompoundButton.OnCheckedChangeListener它在你意想不到的时候开火。

想象一下,您有 100 首歌曲,每首歌曲一开始都不是您最喜欢的。您激活CompoundButton与歌曲 #5 相关的关联,这会触发它OnCheckedChangeListener并将歌曲 #5 标记为您的数据库中的收藏夹。然后向下滚动,直到第 5 首歌曲不再出现在屏幕上。

在某些时候,ViewHolder之前与歌曲 #5 相关联的 将被回收,然后重新用于显示另一首歌曲。在那个时间点,onBindViewHolder()将被调用。这将触发这一行:

holder.favorite.setChecked(songs.getFavorite());
Run Code Online (Sandbox Code Playgroud)

请记住,这ViewHolder曾经与歌曲 #5 相关联,因此在此行运行之前CompoundButton检查。由于新的歌曲是不是最喜欢的,这条线会改变CompoundButton,这样不被选中。

这将触发onCheckedChangeListener. 除了此时,听众还没有被重新分配,所以仍然指的是歌曲 #5。由于CompoundButton已从选中更改为未选中,因此听众会将歌曲 #5 标记为您的数据库中不是最喜欢的。

然后听众被重新分配,现在指的是新歌。但在这一点上,损害已经造成。

你可以通过简单地添加来解决这个问题

holder.favorite.setOnCheckedChangeListener(null);
Run Code Online (Sandbox Code Playgroud)

在开头onBindViewHolder()