Changing layout properties during runtime

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.

Getting ready

Here we will set up a simple layout with XML and use a LinearLayout.LayoutParams object to change ...

Get Android Application Development Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.