我一直卡在代码中,我想更改 Activity 项目的适配器项目图像源。我已全部设置完毕,仍在获取 Activity 项位置并从服务中调用方法。
我有 sendBroadcast
方法来发送带有一些数据的 Intent ,并在包含 RecyclerView
的 fragment 中接收它。
然后从 onReceive()
方法调用适配器方法。问题来了。在 Adapter 中,一切都运行良好,直到记录日志。
问题是元素需要一个支架才能更换,比如
holder.imageview.setBackgroundResource(...);
但即使在 notifyDatasetChanged();
之后它也无法正常工作 请帮助我,伙计们,
下面是我的代码。
这些是在需要时调用的服务方法:
public void sendPlayBroadcast() {
controlIntent.putExtra("control", "1");
sendBroadcast(controlIntent);
Log.e("sending broadcast","TRUE");
}
public void sendPauseBroadcast() {
controlIntent.putExtra("control", "0");
sendBroadcast(controlIntent);
Log.e("sending broadcast","TRUE");
}
这是 fragment ,我接收广播并调用适配器方法:
BroadcastReceiver controlBR = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
sendControls(intent);
}
};
private void sendControls(Intent cIntent) {
String controls = cIntent.getExtras().getString("control");
int control = Integer.parseInt(controls);
switch (control) {
case 1:
mAdapter.Play_the_Icon();
mAdapter.notifyDataSetChanged();
Log.e("received broadcast","TRUE");
break;
case 0:
mAdapter.Pause_the_Icon();
mAdapter.notifyDataSetChanged();
Log.e("received broadcast","TRUE");
break;
}
}
这些是 RecyclerView
适配器:
public void Pause_the_Icon() {
imageView.setImageResource(R.drawable.ic_play_arrow_24dp);
Log.d("all good till here", "TRUE");
}
public void Play_the_Icon() {
imageView.setImageResource(R.drawable.ic_equalizer_24dp);
Log.d("all good till here", "TRUE");
}
最佳答案
您需要在onBindViewHolder()
方法中更新图片资源,否则您的更改将会丢失。
这是我的建议:
1) 在您的适配器中创建一个int
变量来引用资源文件。
private int mImgResource;
2) 使用默认值在适配器构造函数中初始化变量,例如:
mImgResource = R.drawable.ic_equalizer_24dp;
3) 将您的 Pause_the_Icon()
和 Play_the_Icon()
方法更改为:
public void Pause_the_Icon() {
mImgResource = R.drawable.ic_play_arrow_24dp;
Log.d("all good till here", "TRUE");
}
public void Play_the_Icon() {
mImgResource =R.drawable.ic_equalizer_24dp;
Log.d("all good till here", "TRUE");
}
4) 在您的onBindViewHolder()
方法中,执行:
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.imageview.setBackgroundResource(mImgResource);
}
关于android - 如何从 bindViewHolder 中更改 Adapter 项目资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35521140/