2012-05-16 106 views
0

View leader,我不知道是什麼,第二個參數應該是的Android tablelayout麻煩,加上我有麻煩意見

 TableLayout leaderTable = (TableLayout)findViewById(R.id.leaderTable);    

     TableRow tr = new TableRow(this); 
     tr.setId(i); 
     tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT)); 

     View leader = new View(UserView.this, null, R.id.leaderLayout); 

     TextView number = (TextView)leader.findViewById(R.id.numberView); 
     number.setText(String.valueOf(i+1)); 

     tr.addView(leader); 

     leaderTable.addView(tr); 

的問題是,我TextView爲空,儘管是一個子視圖leader.

很困惑這個問題,這是我的XML

<TableLayout 
       android:id="@+id/leaderTable" 
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:gravity="center"> 

      </TableLayout> 

我需要用XML做多?我不需要在其中包含表格嗎?

R.id.leaderLayout是自己的XML文件,與該ID

回答

1

這裏一個LinearLayout中對視圖構造的開發者頁面:如果您

https://developer.android.com/reference/android/view/View.html#View%28android.content.Context%29

的角度對第二和第三個參數用於希望此視圖在創建該視圖時設置某些屬性或樣式。

它看起來像你實際上想要你的變量leader被誇大。這將採用xml定義的佈局,並將其分配給動態創建的視圖。你說你的leaderLayout是一個LinearLayout,所以它看起來像這樣。

//Initialize the layout inflator, do this once and use it to inflate as many views as you want 
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

//Assign your custom view to the variable leader 
LinearLayout leader = (LinearLayout) inflator.inflate(R.layout.leaderLayout, tr); 

充氣的第一個參數是R.layout。 nameOfYourXmlFile。第二個是ViewGroup,它將成爲你的虛擬View的父代。完成此操作後,您可以使用Leader上的findViewById來獲取Xml文件中的子視圖,動態添加更多子項並將其添加爲TableRow的子項。

以下是LayoutInflator的開發者頁面,以防您對inflate方法的其他用法感到好奇。

http://developer.android.com/reference/android/view/LayoutInflater.html

+0

我有一個新的錯誤,現在,這裏是我真的triyng做http://codepad.org/3c4NNFlY,在addView失敗'05-16 13 for循環的第二次:34:05.143:E/AndroidRuntime(855):java.lang.IllegalStateException:指定的子項已經有父項。您必須先調用子對象的父對象的removeView()。 '我想這絕不會是一個問題,因爲所有視圖都是唯一的,並且在for循環的每一遍都創建。 – CQM

+1

「膨脹」方法的第二個參數是膨脹視圖的父級。由於視圖不能是多個父項的子項,因此您在「addView」上發生錯誤,因爲父項已被設置。如果您將tr作爲參數傳遞,則應該自動添加而不需要addView。或者,您可以只用第一個參數調用充氣,佈局文件,然後按照原樣調用addView。 – MattDavis