|Android Programming In Java: Programming the UI|
|Written by Mike James|
|Monday, 03 June 2019|
Page 3 of 3
Programming Layout Properties
At the moment we are relying on default settings for the properties, and the layout properties in particular, of the View objects we are creating. However, in practice you could spend the time and lines of code to set all of the properties needed to create any user interface and layout you wanted to.
You now know how to create a UI completely in code. All you have to do is create all of the objects you need, set their properties and add them to suitable layout objects. This is a little more complicated than you might think because each layout type has a different set of layout properties. Exactly how this is done is easy enough, but if you don't want to know about it at this stage you can skip ahead as it doesn't change any of the general principles.
As explained in the previous chapter, each type of Layout has an associated class derived from LayoutParams called layout.LayoutParams where layout is the name of the Layout class. For example, LinearLayout has the LinearLayout.LayoutParams class, which is used to define all of the layout properties that a View object can use when added to a LinearLayout object.
You can probably guess how to make use of the LayoutParams class. All you do is create a correctly initialized instance of the appropriate LayoutParams class and use setLayoutParams on any View object you want to customize.
For example, to set the height and width in a LayoutParams object we could use:
There is a constructor for all of the LayoutParams classes that accepts just the width and the height properties. Once you have a LayoutParams object you can assign it to any View object by setting the View object’s LayoutParams property:
With this change the third button in our previous layout will be exactly 100 by 100 pixels.
Notice that the constructor works in pixels, i.e. px, instead of device-independent pixels, dp. You can also use constants for MATCH_PARENT and WRAP_CONTENT. For example:
There is also a constructor that allows you to set the weight. Other layout properties have to be set using setProperty methods after the constructor has done its job. For example:
which sets the left, top, right and bottom margins accordingly:
More complex Layout objects have correspondingly more complex LayoutParams that you have to spend time setting up.
So to be clear – there are properties such as Text that you set directly on the View object, but there are also Layout properties that you have to set on an appropriate LayoutParams object, which is then set as the View object's LayoutParam property.
Not included in this extract:
|Last Updated ( Monday, 03 June 2019 )|