Change xml layout to java code

Hi, can anyone say how we can change the xml layout to Java code. I need to show the grid view inside the tab view. To do this, I need to implement these attributes in Java code, not in 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" 
+4
source share
2 answers

let's say you have access to the grid:

 final GridView gw = [...]; 

To set all the attributes above you must 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); 

To install LayoutParams you must choose between the two situations described above.

+6
source

You can either create a new GridView.LayoutParams object and then pass it to setLayoutParams(...) or use the methods associated with the XML attributes to set each individual 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 GridView.LayoutParams through myParams.someMethodName(...) . You will find methods and supported parameters in the link above.

You will then pass the LayoutParams object to your view through myGridView.setLayoutParams(myParams);

+1
source

All Articles