About Android padding, margin, width, height, wrap_content, match_parent, R Class
Padding and Margin
padding
and layout_margin
are two very similar attributes. Both determine the space around a View. The difference is that padding
determines space within the boundaries of the view, and layout_margin
determines the space outside the boundaries of the view.Width and Height
Some of the most important properties are the width property and height property - those must be defined for every view. Remember that all views occupy a rectangular area on the screen - the width and height are the width and height of that area. You can define this in pixels, or better yet dp (stands for density-independent pixels):
android:layout_width="200dp"
android:layout_height="300dp"
For the sake of having a layout be responsive and adjust to different devices, two common values are not numbers at all, but
wrap_content
and match_parent
used as shown here:android:layout_width="wrap_content"
android:layout_height="match_parent"
wrap_content will shrink the view to wrap whatever is displayed inside the view. For example, if the view is filled with the text “Hello world” then
wrap_content
for the width will set the width of the view to be the exact width that the text “Hello world” takes up on the screen.
match_parent will expand the size of the view to be as large as the parent view which it is nested inside of.
The R Class
When your application is compiled the R class is generated. It creates constants that allow you to dynamically identify the various contents of the
res
folder, including layouts. To learn more, check out the documentation about resources.setContentView
So what is the
setContentView
method doing? It inflates the layout. Essentially what happens is that Android reads your XML file and generates Java objects for each of the tags in your layout file. You can then edit these objects in the Java code by calling methods on the Java objects. We’ll go over what these methods look like and how to access view in your layout files later in the course.