In Android development, it's generally the preferred practice to define the UI with XML and the application code in Java, keeping the User Interface code separate from the application code. There are times where it is much easier or more efficient, to alter (or even build) the UI from the Java code. Fortunately, this is easily supported in Android.
We saw a small example of modifying the layout from code in the previous recipe, where we set the number of GridView
column to display in the code. In this recipe, we will obtain a reference to the LayoutParams
object to change the margin during runtime.
Here we will set up a simple layout with XML and use a LinearLayout.LayoutParams
object to change the margins of a View during runtime.