01 Android Layouts and XML Flashcards
Android apps are divided into two parts
- Resources
2. Java code
Resources include
● Layouts (define structure of UIs) ● Drawables o graphics such as PNGs o XML files that describe how to draw Shapes ● Strings ● Colors ● Menus ● Styles (sort of like CSS) ● Other miscellaneous things
Java Code
● All the logic that runs
● Code you write
● Code you get from the Framework
Layouts and Views
Every UI “widget” in Android is called a View Views can be “singular”
Buttons, TextViews, Checkboxes, etc
- Views can also be used to lay out other views
● Called “ViewGroups”
● Have child views
● Each ViewGroup has different rules for
organizing its children
Other Info on the Layout
match_parent == Make me as big as the thing I’m inside. If I’m the top-most thing, make me as big as the screen
wrap_content == Make me only as big as the stuff I am displaying 60dp == Make me exactly 60 units big*
Dp = Density Independent Pixels (more on density later) * Assuming there is enough space
android:id=”@+id/my_label”
@ Put this in the “id” group
+ Create a new one if it doesn’t exist my_label The name of the id.
On the Java side, this becomes: R.id.my_label
Finding and Using Views in Java
In an Activity
TextView myText =
(TextView)findViewById(R.id.label)
In Fragments, or if you have a ViewGroup and want to find its children
Button button =
(Button)findViewById(R.id.my_button)
• The cast to Button or TextView is needed
because the declared return type is View
• FindViewByID is slow, so it is best to do it
once for each control in the onCreate
function, and never again
Inflating Resources
Each screen in an Android app implemented using a Java class called an Activity*
When an Activity is created, you tell the Android SDK which layout file to use
The conversion from XML to Java is called “inflating”
Inflating Resources (resource id)
Whenever your app needs to create UI, your Java code specifies what layout to use by providing a layout “resource Id”
R.layout.activity_main
R = Your app's resources layout = pick something in the "layout" folder(s) activity_main = The name of the layout
Inflating Resources (layout file)
Choices, choices... Android automatically picks the layout file that best fits the "current configuration" of the device ● Landscape vs. Portrait ● Language ● Screen Size ● Screen Density*
Inflating Resources (name, structure)
All resources are assigned an ID
Multiple versions of a resource can exist
Structured according to the type/folder the resource is in
Anything with the same name, but in different folders, get assigned the same ID
Creating Views in Java
Its possible (but usually not recommended) to create Views directly in Java
You have to manually code each device configuration
LayoutParams are a pain
Beginner Views to Know
TextView EditText Button FrameLayout LinearLayout RelativeLayout (Lab 1) ScrollView / HorizontalScrollView