2013-12-09 58 views
0

我試圖運行ListView.getChildAt()方法後,我調用了ListView的setAdapter(),但它給我NullPointerException。看起來設置適配器不會導致創建子視圖。正如下面的方法所告訴的,我試圖獲取子視圖,以便我可以更改其背景顏色。我該如何解決這個問題?設置適配器後調用ListView的getChildAt()方法

private void showAnswers(int questionLocation) 
{ 
    List<Answer> answers = getAnswersByQuestionLocation(questionLocation); 

    ArrayAdapter<String> answerAdapter = new ArrayAdapter<String>(this, 
            android.R.layout.simple_list_item_activated_1); 

    for (int i = 0; i < answers.size(); i++) 
    { 
     answerAdapter.add(mOptionLetters[i] +". "+ answers.get(i).getAnswerText()); 
    } 

    mAnswerList.setAdapter(answerAdapter); 

    if (mAnswerLocationByQuestionLocation.indexOfKey(questionLocation) > -1) 
    { 
     Log.v("Child Count",String.valueOf(mAnswerList.getChildCount())); 

      //mAnswerList.getChildAt(
      //  mAnswerLocationByQuestionLocation.get(questionLocation)) 
      //  .setSelected(true); 
    } 
} 

回答

3

如果你所有的需要的是改變的背景下, 這裏它是如何工作的:

ArrayAdapter<String> answerAdapter = new ArrayAdapter<String>(this, 
      android.R.layout.simple_list_item_activated_1) { 
     @Override 
     public View getView(int position, View convertView, 
       ViewGroup parent) { 
      View v =super.getView(position, convertView, parent);; 
      v.setBackgroundColor(Color.RED); 
      return v; 
     } 

    }; 

因爲你在UI線程上運行,列表視圖將需要足夠的時間來創建在線程中的下一個循環中查看,但是您無法猜測何時。 所以最好的辦法是重寫getView在適配器,因爲該適配器的Feed孩子的ListView的:)


class MyModel { 

      public MyMode(String txt){ 
      this.txt = txt 
      } 

     public String txt; 
     public boolean isSelected; 

     @Override 
     public String toString() { 
      return txt; 
     } 
    } 

ArrayAdapter<MyModel> answerAdapter = new ArrayAdapter<MyModel>(this, 
     android.R.layout.simple_list_item_activated_1) { 
    @Override 
    public View getView(int position, View convertView, 
      ViewGroup parent) { 
     View v =super.getView(position, convertView, parent);; 
     MyModel model = getItem(position); 
     if(model.isSelected){ 
      v.setBackgroundColor(Color.RED);} 
     else{ 
      v.setBackgroundColor(Color.WHITE);} 
     return v; 
    } 

}; 

answerAdapter.add(new MyModel(mOptionLetters[i] +". "+ answers.get(i).getAnswerText())); 

if (mAnswerLocationByQuestionLocation.indexOfKey(questionLocation) > -1) 
    { 
     MyModel model = (MyModel)mAnswerList.getItemAtPosition(questionLocation); 
    model.isSelected= true; 
    answerAdapter.notifyDataSetChanged(); 

    } 
} 

無論如何,你需要閱讀本教程有關ListViews和適配器 http://www.vogella.com/articles/AndroidListView/article.html

+0

沒有。當有人點擊導航頁面上的下一個或上一個按鈕時,我正在更改背景,以便所選答案可以保留並顯示給用戶。 – Tarik

+0

因此,您必須使用具有「標誌」的'Model'來選擇此答案,然後通知適配器重新創建視圖。 –

+0

任何代碼示例? – Tarik

相關問題