我想在RecyclerView中更改ImageView的图像.
例如 :
我在RecyclerView中有30个项目,当我单击位置1上的项目时,项目将图像从播放更改为暂停,然后当我向下滚动到位置15并单击“播放”按钮时,选择了上一个按钮(项目1 )应将图像更改回播放状态,而第15项图像应更改为暂停.我已经在onbindViewHolder内部实现了onClicklistener.但是,它更改了错误项目中的图像.
请帮我
if (mediaPlayer != null) {
mediaPlayer.reset();
mediaPlayer.stop();
LinearLayout view = (LinearLayout) recyclerView.getChildAt(pos);
ImageView button = (ImageView) view.findViewById(R.id.playbutton);
button.setImageResource(R.drawable.ic_play_arrow_black_24dp);
}
playbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isPlaying = sharedPreferences.getBoolean(ConstantValue.ISPLAYING, false);
RecordingDetail recordingDetail = list.get(getAdapterPosition());
if (!isPlaying) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(ConstantValue.ISPLAYING, true);
editor.putInt(ConstantValue.CURRENTINDEX, getAdapterPosition());
editor.commit();
playbutton.setImageResource(R.drawable.ic_pause_black_24dp);
mediaPlayerControl.Play(recordingDetail.path, getAdapterPosition(), progressBar);
}
这里的播放按钮是我要更改的图像视图,mediaPlayerControl是接口
解决方法:
您可以使用全局字段来跟踪所选位置,然后检查是否在onBindViewHolder中选择了当前视图.另外,我强烈建议您在ViewHolder内部分配onClickListener.
>声明一个全局变量:
private int selectedPosition = -1;
>然后在onClick中设置所选位置,然后调用notifyDatasetChanged:
@Override
public void onClick(View view) {
selectedPosition = getAdapterPosition();
if (mediaPlayer != null) {
mediaPlayer.reset();
mediaPlayer.stop();
}
RecordingDetail recordingDetail = list.get(selectedPosition);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(ConstantValue.ISPLAYING, true);
editor.putInt(ConstantValue.CURRENTINDEX, selectedPosition);
editor.commit();
mediaPlayerControl.Play(recordingDetail.path, selectedPosition, progressBar);
notifyDatasetChanged();
}
>最后检查onBindViewHodler中的选定位置并设置适当的图像:
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
LinearLayout view = holder.linearLayout;
ImageView button = (ImageView) view.findViewById(R.id.playbutton);
if (position == selectedPosition) {
button.setImageResource(R.drawable.ic_pause_black_24dp);
} else {
button.setImageResource(R.drawable.ic_play_arrow_black_24dp);
}
}
编辑
正如@shalafi所建议的那样,您不应保留对RecyclerView适配器内特定视图的引用,因为视图已被回收(重用).