2013-09-29 19 views
0

我讓我的充氣器顯示了我想要的行數。我無法將文本插入到充氣機內的每個文本視圖中。它只填充第一個TextView並將其餘部分留空。我嘗試使用數組,但一直得到運行時錯誤將文本添加到TextView裏面的充氣器

  for (int i = 1; i <= numberOfGuests; ++i) { 
      LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      View view = inflater.inflate(R.layout.row_per_person, table); 
      float numberInsertedForPerson = (float) (Math.round(tipPerPersons * 100.0)/100.0); 
      String sTipPerPerson = Float.toString(numberInsertedForPerson); 
      tipPerPerson = (TextView) findViewById(R.id.tipPerPerson); 
      tipPerPerson.setText(sTipPerPerson); 

     } 

回答

2

你的問題是(在我看來)的LayoutInflater相當混亂行爲。

首先,您應該緩存引用,而不是在每次迭代中獲取LayoutInflater。其次,當您撥打inflate(int, ViewGroup)方法時,它實際上會返回第二個參數(ViewGroup),而不是膨脹的View。答案是將第三個參數(無論是否應附加View)傳遞爲false。這會給你充氣View,然後你可以附加到父母ViewGroup。正確的方法如下所示:

LayoutInflater in = getLayoutInflater(); 

for (int i = 1; i <= numberOfGuests; i++) { 
    View v = in.inflate(R.layout.row_per_person, table, false); 
    float num = (float) (Math.round(tipPerPersons * 100.0)/100.0); 
    String tip = Float.toString(num); 
    tipPerPerson = (TextView) v.findViewById(R.id.tipPerPerson); 
    tipPerPerson.setText(tip); 
    table.addView(v); 
} 
+0

當我添加false時,infalter不再有效。 – Aaron

+0

它的工作原理,我只是忘記提及另一個事實,那就是當你傳遞false時,它不會被添加到父ViewGroup中。檢查我最近的編輯 - 你需要在最後調用'addView()'。 – kcoppock

+0

謝謝,它是我第一個在一年半內完成的Android項目,我不記得它很多,並且不在工作中使用java – Aaron

0

而不是使用findViewById,你應該在這兒加上view.findViewById

相關問題