2

我一直卡在代碼中,我想更改活動項目的適配器項目圖像源。我已經設置好了,仍然獲得活動的項目位置並從服務中調用該方法。如何更改適配器項目資源bindViewHolder

我有sendBroadcast方法發送意圖與一些數據,並在包含RecyclerView的片段中接收它。

並從那裏onReceive()方法我調用適配器方法。問題出現了。在適配器中它一直運行良好,直到日誌記錄。

的問題是,該項目需要一個支架,以便它可以改變的,就像

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"); 
} 

這片段,我接收廣播和調用適配器方法:

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適配器:

​​

回答

1

您需要更新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); 
} 
+0

正要試試這個 –

+1

它實際上工作!謝謝。 –