将xml布局更改为java代码

Ani*_*ish 4 android

嗨,任何人都可以告诉我们如何将xml布局更改为java代码.我需要在选项卡视图中显示网格视图.为此我需要在Java代码而不是xml中实现这些属性.请回复

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"
Run Code Online (Sandbox Code Playgroud)

rek*_*eru 6

假设您已访问网格视图:

final GridView gw = [...];
Run Code Online (Sandbox Code Playgroud)

要设置上面的所有属性,您应该写:

// 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);
Run Code Online (Sandbox Code Playgroud)

要设置LayoutParams,您必须在上述两种情况之间进行选择.