2016-11-17 18 views
0

我使用RecyclerView來顯示TextViews列表。我想要位置0,1,2,3和4的TextView有一個彩色正方形。這是我的代碼:RecyclerView適配器的方法holder.getAdapterPosition()滾動後得到錯誤的值

@Override 
    public void onBindViewHolder(final ViewHolder holder, int position) { 

     holder.mItem = mValues.get(position); 

     if(holder.getAdapterPosition()==0) { 

      holder.lytColor.setBackgroundColor(Color.rgb(255, 201, 8)); 

     } else if(holder.getAdapterPosition()==1) { 

       holder.lytColor.setBackgroundColor(Color.rgb(242, 157, 32)); 

     }else if(holder.getAdapterPosition()==2) { 
      holder.lytColor.setBackgroundColor(Color.rgb(177, 134, 66)); 

     }else if(holder.getAdapterPosition()==3) { 

      holder.lytColor.setBackgroundColor(Color.rgb(123, 102, 72)); 

     }else if(holder.getAdapterPosition()==4){ 
       holder.lytColor.setBackgroundColor(Color.rgb(77,72,69)); 

     } 
    } 

它的工作原理:

enter image description here

的問題是,當我向下滾動其他TextViews也有顏色:

enter image description here

我已經使用Log.e(「test」,getAdapterPosition())來查看位置,並且它顯示了期望值,該項目在ArrayList中的位置。

在我的手機它遵循下一個模式:5色,10無色,有色5,10無色...

我測試過的其他手機應用程序使用更大的屏幕和格局的變化,5有色,13無色,5色,13無色...

所以我假設可以在屏幕上顯示的項目數與問題有關。

PS:我已經嘗試過使用位置參數

有什麼建議嗎?

+0

你嘗試過使用getLayoutPosition()嗎? –

+0

試試這個getOldPosition() –

+0

謝謝,但那些方法沒有工作 – ChocoboGordo

回答

1

是的你是對的!適配器中的位置將回收它的適配器性質。

你可以做的是在你的模型中取一個變量讓我們說colourId。在添加到列表中時,請將值分配給它。例如說colourId = 1,2,3等等。

,並得到像下面

mValues.get(position).getCoulourId(); 

比應用該值的條件下,如果在適配器值。

+0

謝謝!有效。但是我仍然想知道爲什麼這個位置在日誌消息中是正確的,而不是在if條件下 – ChocoboGordo

相關問題