Overview
XML (Extensible Markup Language) is extensively used in Android development to define the user interface (UI) layouts. It allows developers to separate the presentation and logic layers, making the code more organized and maintainable. XML layouts describe the visual structure of the UI, specifying the arrangement and attributes of various UI components.
Key Concepts
- Layout Resource
- XML files are used to define the structure of the UI.
- Stored in the
res/layout
directory. - Each XML file represents a layout resource that can be referenced in the Android application.
- Hierarchy of Views
- UI components in Android are built using a hierarchy of views.
- The view is the building block of the User Interface.
- Layouts are view groups that define the positioning and sizing of child views.
- Root Element
- Each XML layout file has a single root element.
- The root element is typically a layout container like
LinearLayout
,RelativeLayout
, orConstraintLayout
.
- Attributes
- Elements within the XML file have attributes that define their properties.
- Common attributes include
android:id
,android:layout_width
,android:layout_height
,android:padding
, etc. - Attributes can be specified directly or using resource references.
Common Layout Types
- LinearLayout
- Arrange widgets in a row or column.
- The
orientation
the attribute specifies the direction (horizontal or vertical). - Can nest other LinearLayouts to create complex layouts.
- RelativeLayout
- Position your view relative to each other or parent.
- Flexible but can become complex with many child views.
- ConstraintLayout
- Most flexible layout, allowing precise control over the positioning of child views.
- It uses constraints to define the relationships and positioning of views.
- FrameLayout
- They block the whole user interface and show only one item.
- All view that act as children in a stack, the most recent on top of the stack.
- TableLayout
- Arrange its children into rows and columns.
- Consists of
TableRow
elements, each containing multiple child views.
Views
- TextView
- Displays text to the user.
- Common attributes include
android:text
,android:textSize
, andandroid:textColor
.
- EditText
- These widgets allow the user to input their desired text.
- Common attributes include
android:hint
,android:inputType
, andandroid:maxLength
.
- Button
- A clickable button.
- Common attributes include
android:text
andandroid:onClick
.
- ImageView
- Displays an image.
- Common attributes include
android:src
andandroid:contentDescription
.
- CheckBox
- A checkbox that can be checked or unchecked.
- Common attributes include
android:text
andandroid:checked
.
- RadioButton
- A radio button may select or deselect.
- Typically used within a
RadioGroup
to allow only one selection.
- ProgressBar
- Indicates progress.
- Common attributes include
android:indeterminate
andandroid:progress
.