IT272 Mobile Application Development

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 View subclasses (e.g., Button, EditText, ImageView) that perform specific functions.
  • ViewGroup: A special View that 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 : contains

Real-World Example: eSewa App

  • Which idea? Uses Button, EditText, and ImageView widgets for payment forms.
  • How? The "Pay Now" button is a Button widget with an onClickListener to trigger payment logic. The QR code is an ImageView loaded 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 (LinearLayout with TextView for item names and Button for "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 + Button pairs 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:
    1. logo anchors to top of parent.
    2. phoneNumber anchors below logo with max width.
    3. rechargeBtn anchors below phoneNumber.

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:

  1. 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.

  2. Layout Qualifiers:

    • layout-sw600dp: For screens ≥600dp width.
    • layout-land: For landscape orientation.
  3. 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 ConstraintLayout with dynamic constraints.
    • Override res/layout-sw600dp/activity_stock.xml to show 2 columns.

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

  1. Khalti App

    • Idea: Uses ConstraintLayout for dynamic QR code alignment.
    • How: The QR code (ImageView) resizes based on screen width while keeping margins consistent via constraints.
  2. NTC Electricity Bill App

    • Idea: RecyclerView with CardView for bill history.
    • How: Each bill is a ViewHolder with TextView for date/amount and Button for "Pay."
  3. Google Maps (Android)

    • Idea: Adaptive UI with Fragment for search vs. map views.
    • How: Switches between MapFragment and SearchFragment based on screen size (tablets show both side-by-side).

Exam Tip

  1. XML Syntax: Memorize common tags (<Button>, <EditText>, <ConstraintLayout>) and attributes (layout_width, id).
  2. Layout Comparisons: Know when to use LinearLayout (simple), RelativeLayout (legacy), or ConstraintLayout (modern).
  3. Adaptive UI: Questions often ask how to handle screen sizes/orientations. Always mention dimens.xml or layout qualifiers.
  4. Visual Hierarchy: Draw a simple UI (e.g., login screen) and label its ViewGroup structure.
  5. Common Pitfalls:
    • Forgetting android:id for programmatic access.
    • Using match_parent in nested LinearLayouts (causes MeasureSpecException).
    • Ignoring dp vs. sp for text sizing.

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…