0

我想滾動回收視圖和更改回收站視圖中給定項的背景,因爲它滾動同步到Android TTS引擎,滾動工作沒有問題,但一旦有太多的項目在視圖中,不斷變化的背景突破(NPE),我相信它是因爲回收者視圖如何破壞孩子,但是有點新手,我不確定這裏是我的滾動代碼視圖滾動回收視圖和編輯子空間背景給空指針異常

public void onInit(int initStatus) { 
    if (initStatus == TextToSpeech.SUCCESS) { 
     myTTS.setLanguage(Locale.UK); 
     //myExclusiveTTS.setLanguage(Locale.UK); 
     myExclusiveTTS.setOnUtteranceProgressListener(new UtteranceProgressListener() { 
       @Override 
       public void onDone(String utteranceId) { 

        runOnUiThread(new Runnable() { 
         @Override 
         public void run() { 
          System.out.println("onDone " + cardCountPosition +" list size " + SpeakGridDB.cardMakerList.size()); 
          SpeakGridDB.recyclerView.getLayoutManager().getChildAt(cardCountPosition).setBackgroundResource(R.drawable.border); 
          cardCountPosition ++; 
          if(cardCountPosition == SpeakGridDB.cardMakerList.size()){ 
           System.out.println("onDone if " + cardCountPosition +" list size " + SpeakGridDB.cardMakerList.size()); 
           cardCountPosition = 0; 

          } 
         } 
        }); 

       } 

       @Override 
       public void onError(String utteranceId) { 
       } 

       @Override 
       public void onStart(String utteranceId) { 
        System.out.println("onStart " + cardCountPosition +" list size " + SpeakGridDB.cardMakerList.size()); 
        moveView(); 
       } 
      }); 

    } else if (initStatus == TextToSpeech.ERROR) { 
     Toast.makeText(this, "Oops sorry! Text To Speech failed... SimpleAAC cannot fix this", Toast.LENGTH_LONG).show(); 
    } 
} 

public void moveView(){ 
    runOnUiThread(new Runnable() { 
     @Override 
     public void run() { 
      if (cardCountPosition < SpeakGridDB.cardMakerList.size()){ 
       SpeakGridDB.recyclerView.getLayoutManager() 
         .smoothScrollToPosition(SpeakGridDB.recyclerView, null, cardCountPosition + 1); 
       SpeakGridDB.recyclerView.getLayoutManager().getChildAt(cardCountPosition).setBackgroundResource(R.drawable.selected_blue_border); 

      } 
      else{ 
       //this never gets called 
       cardCountPosition = 0; 
      } 

     } 
    }); 
} 

我的NPE來自moveView方法@

SpeakGridDB.recyclerView.getLayoutManager() 
.getChildAt(cardCountPosition).setBackgroundResource 
(R.drawable.selected_blue_border); 

如果我只有在視圖中1,2,3或4項,將工作沒有失敗,我的打印輸出看起來像這樣

I/System.out: onStart 0 list size 3 
I/System.out: onDone 0 list size 3 
I/System.out: onStart 1 list size 3 
I/System.out: onStart 1 list size 3 
I/System.out: onDone 1 list size 3 
I/System.out: onDone 2 list size 3 
I/System.out: onDone if 3 list size 3 

任何4次以上(約適合在屏幕上有多少個項目)與NPE崩潰,但我的打印輸出看起來與任何人可以提出好的建議我需要檢查之前,我設置視圖

回答

0

的背景資源找到了一個答案,這在另一篇文章,現在我使用

SpeakGridDB.recyclerView.findViewHolderForAdapterPosition 
(cardCountPosition).itemView.setBackgroundResource(R.drawable.border); 

取數從視圖保持器而不是隻考慮視圖的適配器