2011-04-20 107 views
4

嗨 可以任何一個告訴我們如何將xml佈局更改爲java代碼。 我需要顯示標籤視圖內的網格視圖。爲此,我需要實現的Java代碼,而不是XML這些屬性,請您及時回覆將xml佈局更改爲java代碼

android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:numColumns="auto_fit" 
android:verticalSpacing="10dp" 
android:horizontalSpacing="10dp" 
android:columnWidth="90dp" 
android:stretchMode="columnWidth" 
android:gravity="center" 

回答

6

說你有訪問網格視圖:

final GridView gw = [...]; 

對於設置的所有屬性上面,你應該寫:

// This line applies to a GridView that you've just created 
gv.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); 
// The next two lines are for a GridView that you already have displayed 
gv.getLayoutParams().width = LayoutParams.FILL_PARENT; 
gv.getLayoutParams().height = LayoutParams.FILL_PARENT; 

gv.setNumColumns(GridView.AUTO_FIT); 
gv.setVerticalSpacing(convertFromDp(10)); 
gv.setHorizontalSpacing(convertFromDp(10)); 
gv.setColumnWidth(convertFromDp(90)); 
gv.setStretchMode(GridView.STRETCH_COLUMN_WIDTH); 
gv.setGravity(Gravity.CENTER); 

要設置LayoutParams,您必須在上述兩種情況之間進行選擇。

+0

可否請你解釋convertFromDp()也 – 2011-11-28 08:41:57

1

您可以創建一個新的GridView.LayoutParams對象,然後把它傳遞給setLayoutParams(...)或者您可以使用methods相關的XML屬性從Java設置每個單獨的佈局參數。

只需創建

GridView.LayoutParams myParams = new GridView.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);

然後你可以使用通過myParams.someMethodName(...)GridView.LayoutParams提供的方法。您可以在上面的鏈接中找到方法和支持的參數。

然後你通過通過的LayoutParams對象到您的視圖myGridView.setLayoutParams(myParams);