4

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"

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

could you please explain convertFromDp( ) also
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.