Anish
Anish

Reputation: 4978

change xml layout to java code

Hi can any one tell how we can change the xml layout to java code. I need to show the grid view inside the tab view . For that I need to implement these attributes in Java code rather than xml .Please reply

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"

Upvotes: 4

Views: 5576

Answers (2)

Ben Weiss
Ben Weiss

Reputation: 17922

You can either create a new GridView.LayoutParams object and then pass it to setLayoutParams(...) or you can use the methods associated to the XML attributes to set each single layout parameter from Java.

Just create

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

Then you can use the methods provided by the GridView.LayoutParams via myParams.someMethodName(...). You'll find the methods and supported parameters in the link above.

Then you'll pass the LayoutParams-object to your view via myGridView.setLayoutParams(myParams);

Upvotes: 1

rekaszeru
rekaszeru

Reputation: 19220

say you have the grid view accessed:

final GridView gw = [...];

For setting all the attributes above you should write:

// 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);

For setting the LayoutParams, you must choose between the two situations above.

Upvotes: 6

Related Questions