Mobile Application DevelopmentUnit 49 min read
UI Design & Layouts: Views, Widgets, XML, Constraints & Adaptive UI
Unit 4 of Mobile Application Development covers Android’s UI components (Views, Widgets), layout systems (Linear, Relative, Constraint), XML-based UI design, and responsive/adaptive layouts for different screen sizes and orientations, with real-world app examples and exam-focused comparisons.
Core Concepts
1. Views and Widgets: The Building Blocks
Definition:
- View: The base class for UI elements (e.g., buttons, text fields). Everything visible on-screen inherits from
View. - Widget: Pre-built
Viewsubclasses (e.g.,Button,EditText,ImageView) that perform specific functions. - ViewGroup: A special
Viewthat can hold other Views (e.g.,LinearLayout,RelativeLayout).
How They Work:
Views are rendered in a hierarchy (parent-child relationships). The system draws them in Z-order (topmost first). Widgets are stateful (e.g., a CheckBox remembers if it’s checked).
Visual: Widget Hierarchy
classDiagram
class View {
<<abstract>>
+draw()
+measure()
+layout()
}
class Widget {
<<concrete>>
+onClick()
}
class ViewGroup {
<<concrete>>
+addView(View)
+removeView(View)
}
View <|-- Widget
View <|-- ViewGroup
ViewGroup "1" --> "many" View : containsReal-World Example: eSewa App
- Which idea? Uses
Button,EditText, andImageViewwidgets for payment forms. - How? The "Pay Now" button is a
Buttonwidget with anonClickListenerto trigger payment logic. The QR code is anImageViewloaded dynamically.
2. Layouts: Organizing Views
Android provides three primary layout types, each with trade-offs:
| Layout Type | Description | Pros | Cons | Best For |
|---|---|---|---|---|
| LinearLayout | Arranges child views in a single line (horizontal/vertical). | Simple, easy to use. | Nested layouts can cause performance issues. | Basic forms, lists. |
| RelativeLayout | Positions views relative to each other (e.g., "below Button1"). | No nesting needed; flexible. | Complex XML for advanced layouts. | Dashboards, custom UIs. |
| ConstraintLayout | Uses constraints (anchors) to position views dynamically. | Best performance; supports chains. | Steeper learning curve. | Modern apps (e.g., Pathao UI). |
Visual: LinearLayout vs. ConstraintLayout
[Button1]
[EditText1]
[Button2]
[Button1] --- [EditText1] (top constraint)
[EditText1] --- [Button2] (bottom constraint)
Worked Example: Daraz Order Queue
- Scenario: A user adds items to a cart (
LinearLayoutwithTextViewfor item names andButtonfor "Remove"). - XML Snippet:
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:text="Item 1" /> <Button android:text="Remove" android:id="@+id/removeBtn" /> </LinearLayout> - Trace: Adding 3 items → 3
TextView+Buttonpairs stacked vertically.
3. XML-Based UI Design
Why XML?
- Declarative: Define UI structure separately from logic (MVC pattern).
- Tool Support: Android Studio provides drag-and-drop design tools.
- Reusability: Layouts can be included via
<include>or<merge>.
Key Attributes:
| Attribute | Purpose |
|---|---|
android:layout_width |
wrap_content, match_parent, or fixed dp/px. |
android:layout_height |
Same as above. |
android:id |
Unique identifier (e.g., @+id/usernameEditText). |
android:visibility |
visible, gone, or invisible. |
Visual: XML Structure for a Login Screen
Root (ConstraintLayout)
├── ImageView (Logo)
├── EditText (Username)
├── EditText (Password)
└── Button (Login)
Worked Example: Ncell Recharge UI
- XML Snippet:
<ConstraintLayout ...> <ImageView android:id="@+id/logo" android:src="@drawable/ncell_logo" app:layout_constraintTop_toTopOf="parent" /> <EditText android:id="@+id/phoneNumber" android:layout_width="0dp" app:layout_constraintWidth_max="280dp" app:layout_constraintTop_toBottomOf="@id/logo" /> <Button android:id="@+id/rechargeBtn" android:text="Recharge" app:layout_constraintTop_toBottomOf="@id/phoneNumber" /> </ConstraintLayout> - Trace:
logoanchors to top of parent.phoneNumberanchors belowlogowith max width.rechargeBtnanchors belowphoneNumber.
4. Adaptive UI: Supporting Different Screens
Challenges:
- Screen sizes: Phones (e.g., Samsung Galaxy S22) vs. tablets (e.g., Samsung Tab S8).
- Orientations: Portrait vs. landscape.
- Density:
dp(density-independent pixels) vs.sp(scalable pixels for text).
Solutions:
Dimens.xml: Define sizes in
res/values/dimens.xml:<dimen name="button_height">48dp</dimen> <dimen name="button_height_large">64dp</dimen>Override for large screens in
res/values-sw600dp/dimens.xml.Layout Qualifiers:
layout-sw600dp: For screens ≥600dp width.layout-land: For landscape orientation.
Weight and Bias:
android:layout_weight: Distributes extra space proportionally.app:layout_constraintHorizontal_bias: Adjusts position within constraints.
Visual: Adaptive Layout Example
Portrait:
[Button1][Button2] (LinearLayout, horizontal)
Landscape:
[Button1]
[Button2] (LinearLayout, vertical)
Worked Example: NEPSE App (Stock Prices)
- Problem: Stock tables must reflow for tablets.
- Solution:
- Use
ConstraintLayoutwith dynamic constraints. - Override
res/layout-sw600dp/activity_stock.xmlto show 2 columns.
- Use
5. Common UI Patterns
| Pattern | Description | Example Apps |
|---|---|---|
| Bottom Navigation | Fixed bar at the bottom with icons. | WhatsApp, Instagram. |
| Drawer Navigation | Slide-in menu (e.g., DrawerLayout). |
Gmail, YouTube. |
| RecyclerView | Efficient list/scrollable views (uses Adapter). |
Daraz product listings. |
| Dialogs | Temporary overlays (e.g., AlertDialog). |
eSewa payment confirmation. |
Visual: RecyclerView with Adapter
Data Source (e.g., Firebase)
↓
Adapter (binds data to Views)
↓
RecyclerView (displays items)
↓
ViewHolder (caches Views)
Worked Example: Pathao Driver UI
- Pattern: Bottom navigation for "Home," "Orders," "Earnings."
- XML Snippet:
<com.google.android.material.bottomnavigation.BottomNavigationView android:id="@+id/bottomNav" app:menu="@menu/bottom_nav_menu" /> - Menu Resource (
res/menu/bottom_nav_menu.xml):<menu> <item android:id="@+id/home" android:title="Home" /> <item android:id="@+id/orders" android:title="Orders" /> </menu>
In the Real World
Khalti App
- Idea: Uses
ConstraintLayoutfor dynamic QR code alignment. - How: The QR code (
ImageView) resizes based on screen width while keeping margins consistent via constraints.
- Idea: Uses
NTC Electricity Bill App
- Idea:
RecyclerViewwithCardViewfor bill history. - How: Each bill is a
ViewHolderwithTextViewfor date/amount andButtonfor "Pay."
- Idea:
Google Maps (Android)
- Idea: Adaptive UI with
Fragmentfor search vs. map views. - How: Switches between
MapFragmentandSearchFragmentbased on screen size (tablets show both side-by-side).
- Idea: Adaptive UI with
Exam Tip
- XML Syntax: Memorize common tags (
<Button>,<EditText>,<ConstraintLayout>) and attributes (layout_width,id). - Layout Comparisons: Know when to use
LinearLayout(simple),RelativeLayout(legacy), orConstraintLayout(modern). - Adaptive UI: Questions often ask how to handle screen sizes/orientations. Always mention
dimens.xmlor layout qualifiers. - Visual Hierarchy: Draw a simple UI (e.g., login screen) and label its
ViewGroupstructure. - Common Pitfalls:
- Forgetting
android:idfor programmatic access. - Using
match_parentin nestedLinearLayouts (causesMeasureSpecException). - Ignoring
dpvs.spfor text sizing.
- Forgetting
Mock Question:
"Design a UI for a bank loan calculator with two EditText fields (loan amount, interest rate) and a Button. Use ConstraintLayout and ensure it works on both phones and tablets."
Answer:
<androidx.constraintlayout.widget.ConstraintLayout ...>
<EditText
android:id="@+id/loanAmount"
android:layout_width="0dp"
app:layout_constraintWidth_max="280dp" />
<EditText
android:id="@+id/interestRate"
app:layout_constraintTop_toBottomOf="@id/loanAmount" />
<Button
android:id="@+id/calculateBtn"
app:layout_constraintTop_toBottomOf="@id/interestRate" />
</androidx.constraintlayout.widget.ConstraintLayout>
Adaptive Step: Override res/layout-sw600dp/activity_loan.xml to use GridLayout for tablets.
Based on the TU BITM syllabus for Mobile Application Development (IT272), unit 4.
Discussion
Loading…