2011-04-20 110 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);