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.
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. Create a new project using with an Empty Activity
called RuntimeProperties
. Use the default Phone & Tablet
settings on the Target Android devices
and select Empty Activity
on the Add an Activity to Mobile
dialog.