Layouts & UI

Build flexible Android screens with XML layout managers and responsive design

LinearLayout ConstraintLayout ScrollView Responsive UI

Table of Contents

Layout Overview

Android UI is built from a hierarchy of View objects (widgets) inside ViewGroup containers (layouts). Each layout defines how its children are positioned and sized on screen.

Key sizing attributes: layout_width and layout_height use match_parent (fill container), wrap_content (fit content), or a fixed value in dp (density-independent pixels).

LayoutArrangementWhen to Use
LinearLayoutSingle row or columnSimple stacked or side-by-side UI
RelativeLayoutRelative to siblings or parentLegacy; prefer ConstraintLayout
ConstraintLayoutConstraints between viewsModern default for complex screens
FrameLayoutStacked (top-left default)Fragments, overlays, single child focus
TableLayoutRows and columnsGrid-like data (rare; use RecyclerView for lists)
ScrollViewScrollable containerContent taller than the screen

1LinearLayout

LinearLayout arranges children in a single horizontal or vertical line. Use android:orientation="vertical" or "horizontal".

Vertical login form example

XML — activity_login.xml<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="24dp" android:gravity="center_horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/login_title" android:textSize="24sp" android:textStyle="bold" android:layout_marginBottom="24dp" /> <EditText android:id="@+id/etEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/email_hint" android:inputType="textEmailAddress" android:layout_marginBottom="12dp" /> <EditText android:id="@+id/etPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/password_hint" android:inputType="textPassword" android:layout_marginBottom="16dp" /> <Button android:id="@+id/btnLogin" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/login" /> </LinearLayout>

Important LinearLayout attributes

AttributeDescription
android:orientationvertical or horizontal
android:gravityAlign children inside the layout (e.g. center)
android:layout_gravityAlign a child within its parent LinearLayout
android:layout_weightDivide remaining space proportionally among children
android:dividerDrawable between children (with showDividers)

Horizontal layout with weights

[ Button (weight=1) ] [ Button (weight=2) ] 33% width 67% width
XML — Two buttons sharing width with weight<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Cancel" /> <Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="2" android:text="Confirm" /> </LinearLayout>

2RelativeLayout

RelativeLayout positions children relative to the parent edges or to other views. It was widely used before ConstraintLayout but is now considered legacy for new projects.

Recommendation: Use ConstraintLayout instead of RelativeLayout for new apps — flatter hierarchy, better performance, and visual editor support in Android Studio.

Profile header with avatar and name

XML — fragment_profile_header.xml<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="16dp"> <ImageView android:id="@+id/ivAvatar" android:layout_width="64dp" android:layout_height="64dp" android:layout_alignParentStart="true" android:layout_centerVertical="true" android:src="@drawable/ic_avatar" android:contentDescription="@string/profile_photo" /> <TextView android:id="@+id/tvName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toEndOf="@id/ivAvatar" android:layout_alignTop="@id/ivAvatar" android:layout_marginStart="16dp" android:text="Nikhil Kumar" android:textSize="18sp" android:textStyle="bold" /> <TextView android:id="@+id/tvBio" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/tvName" android:layout_alignStart="@id/tvName" android:layout_marginTop="4dp" android:text="Android Developer" /> <ImageButton android:id="@+id/btnEdit" android:layout_width="40dp" android:layout_height="40dp" android:layout_alignParentEnd="true" android:layout_centerVertical="true" android:src="@drawable/ic_edit" android:contentDescription="@string/edit_profile" /> </RelativeLayout>

Common RelativeLayout rules

RuleEffect
layout_alignParentTop/Bottom/Start/EndAlign to parent edge
layout_centerInParentCenter horizontally and vertically
layout_below / layout_abovePosition relative to another view vertically
layout_toStartOf / layout_toEndOfPosition relative to another view horizontally
layout_alignStart / layout_alignEndAlign edges with another view

3ConstraintLayout

ConstraintLayout is the recommended layout for complex UIs. Views are positioned using constraints — connections to other views or the parent — enabling flat hierarchies and responsive designs without nested layouts.

Add dependency

Kotlin — app/build.gradle.ktsdependencies { implementation("androidx.constraintlayout:constraintlayout:2.1.4") }

Login screen with ConstraintLayout

XML — activity_login.xml<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="24dp"> <TextView android:id="@+id/tvTitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/welcome_back" android:textSize="26sp" android:textStyle="bold" app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" android:layout_marginTop="48dp" /> <EditText android:id="@+id/etEmail" android:layout_width="0dp" android:layout_height="wrap_content" android:hint="@string/email" android:inputType="textEmailAddress" app:layout_constraintTop_toBottomOf="@id/tvTitle" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" android:layout_marginTop="32dp" /> <EditText android:id="@+id/etPassword" android:layout_width="0dp" android:layout_height="wrap_content" android:hint="@string/password" android:inputType="textPassword" app:layout_constraintTop_toBottomOf="@id/etEmail" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" android:layout_marginTop="12dp" /> <Button android:id="@+id/btnLogin" android:layout_width="0dp" android:layout_height="wrap_content" android:text="@string/login" app:layout_constraintTop_toBottomOf="@id/etPassword" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" android:layout_marginTop="24dp" /> <TextView android:id="@+id/tvForgot" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/forgot_password" android:textColor="?attr/colorPrimary" app:layout_constraintTop_toBottomOf="@id/btnLogin" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" android:layout_marginTop="16dp" /> </androidx.constraintlayout.widget.ConstraintLayout>

Essential ConstraintLayout concepts

ConceptDescription
layout_constraint*_*Connect view edges to parent or other views (start, end, top, bottom)
layout_width="0dp"Match constraints — stretch between horizontal constraints
layout_constraintHorizontal_biasPosition between constraints (0.0 = start, 1.0 = end, 0.5 = center)
GuidelineInvisible line at fixed % or dp for alignment reference
BarrierDynamic edge based on the farthest referenced view
ChainGroup views distributed horizontally or vertically
GroupToggle visibility of multiple views together

Horizontal chain (three equal buttons)

XML — Spread chain example<Button android:id="@+id/btnLeft" android:layout_width="0dp" android:layout_height="wrap_content" android:text="Left" app:layout_constraintHorizontal_chainStyle="spread" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toStartOf="@id/btnCenter" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/btnCenter" android:layout_width="0dp" android:layout_height="wrap_content" android:text="Center" app:layout_constraintStart_toEndOf="@id/btnLeft" app:layout_constraintEnd_toStartOf="@id/btnRight" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/btnRight" android:layout_width="0dp" android:layout_height="wrap_content" android:text="Right" app:layout_constraintStart_toEndOf="@id/btnCenter" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" />

4FrameLayout

FrameLayout stacks children on top of each other, aligned to the top-start corner by default. Each child can use layout_gravity to position itself within the frame.

Common uses

  • Fragment container (fragment_container)
  • Image with badge overlay
  • Loading spinner over content
  • Single full-screen child (splash, video player)

Image with badge overlay

XML — item_product_card.xml<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="120dp" android:layout_height="120dp"> <ImageView android:id="@+id/ivProduct" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" android:src="@drawable/product_placeholder" android:contentDescription="@string/product_image" /> <TextView android:id="@+id/tvBadge" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="top|end" android:background="@drawable/bg_badge" android:paddingHorizontal="8dp" android:paddingVertical="4dp" android:text="NEW" android:textColor="@android:color/white" android:textSize="10sp" android:textStyle="bold" /> </FrameLayout>

Fragment host container

XML — activity_main.xml<FrameLayout android:id="@+id/fragment_container" android:layout_width="match_parent" android:layout_height="match_parent" />

5TableLayout

TableLayout arranges children in rows. Each row is typically a TableRow (which behaves like a horizontal LinearLayout). Columns align across rows automatically.

Note: For scrollable or dynamic data tables, prefer RecyclerView. TableLayout suits small, static grids like settings summaries or scoreboards.

Invoice summary table

XML — layout_invoice_summary.xml<TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:stretchColumns="1" android:padding="16dp"> <TableRow> <TextView android:text="Item" android:textStyle="bold" android:padding="8dp" /> <TextView android:text="Amount" android:textStyle="bold" android:gravity="end" android:padding="8dp" /> </TableRow> <TableRow> <TextView android:text="Course Fee" android:padding="8dp" /> <TextView android:text="₹4,999" android:gravity="end" android:padding="8dp" /> </TableRow> <TableRow> <TextView android:text="Discount" android:padding="8dp" /> <TextView android:text="- ₹500" android:gravity="end" android:padding="8dp" /> </TableRow> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="#CCCCCC" android:layout_marginVertical="4dp" /> <TableRow> <TextView android:text="Total" android:textStyle="bold" android:padding="8dp" /> <TextView android:text="₹4,499" android:textStyle="bold" android:gravity="end" android:padding="8dp" /> </TableRow> </TableLayout>

TableLayout attributes

AttributeDescription
android:stretchColumnsColumn index(es) that expand to fill width
android:shrinkColumnsColumn(s) that can shrink if space is tight
android:collapseColumnsHide column(s) initially
android:layout_span (on child)Cell spans multiple columns

6ScrollView

ScrollView (vertical) and HorizontalScrollView let users scroll content that exceeds the screen. A ScrollView can have only one direct child — usually a layout wrapping all content.

Vertical ScrollView with form

XML — activity_registration.xml<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:fillViewport="true"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="24dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/register" android:textSize="24sp" android:textStyle="bold" android:layout_marginBottom="24dp" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/full_name" android:layout_marginBottom="12dp" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/email" android:inputType="textEmailAddress" android:layout_marginBottom="12dp" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/phone" android:inputType="phone" android:layout_marginBottom="12dp" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/address" android:minLines="3" android:gravity="top" android:layout_marginBottom="24dp" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/submit" /> </LinearLayout> </ScrollView>

NestedScrollView (recommended for nested scrolling)

Use androidx.core.widget.NestedScrollView when placing a ScrollView inside CoordinatorLayout, or when nesting with RecyclerView. For long mixed content, consider RecyclerView with multiple view types instead.

ScrollView rules

  • Only one direct child — wrap multiple views in a LinearLayout or ConstraintLayout
  • Set android:fillViewport="true" when content should expand to fill short screens
  • Do not put a RecyclerView inside ScrollView (breaks recycling)
  • Hide keyboard appropriately — use android:windowSoftInputMode="adjustResize" in manifest

7Responsive UI Design

Responsive Android UI adapts gracefully across phone sizes, tablets, foldables, and orientations. Use density-independent units, alternative resources, and flexible layouts.

Units: dp, sp, and px

UnitUse ForWhy
dpPadding, margins, widths, heightsConsistent physical size across screen densities
spText sizeScales with user's font size accessibility setting
pxAvoid in layoutsPixel-exact but wrong on high-DPI devices

Alternative layout folders

Resource qualifiers for layoutsres/ ├── layout/ # Default (phone portrait) ├── layout-land/ # Landscape orientation ├── layout-sw600dp/ # Tablets (smallest width ≥ 600dp) ├── layout-sw720dp/ # Large tablets └── layout-w600dp/ # Available width ≥ 600dp

Tablet two-pane layout (sw600dp)

XML — res/layout-sw600dp/activity_main.xml<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:baselineAligned="false"> <FrameLayout android:id="@+id/list_container" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" /> <FrameLayout android:id="@+id/detail_container" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="2" /> </LinearLayout>

Dimension resources for consistency

XML — res/values/dimens.xml<resources> <dimen name="spacing_small">8dp</dimen> <dimen name="spacing_medium">16dp</dimen> <dimen name="spacing_large">24dp</dimen> <dimen name="text_title">22sp</dimen> <dimen name="text_body">16sp</dimen> </resources>

Responsive design checklist

  • Prefer ConstraintLayout with percentage-based guidelines over fixed pixel sizes
  • Use wrap_content and 0dp (match constraints) instead of hard-coded widths
  • Extract strings, colors, and dimensions to values/ resources
  • Provide layout-land or layout-sw600dp for tablets and landscape
  • Test on small phone (320dp), normal phone (360–411dp), and tablet (600dp+) emulators
  • Support RTL with start/end instead of left/right
  • Use vector drawables (vector XML) so icons scale cleanly

Preview multiple configurations in Android Studio

Layout Editor → Design / Split tab → Device dropdown: Pixel 4, Pixel Tablet, Foldable → Orientation toggle: Portrait / Landscape → Check "Preview all orientations" in layout preview settings

8Hands-On Exercises

1

Build a login screen using LinearLayout (vertical): title, email field, password field, and login button. Center the title horizontally.

2

Recreate the same login screen using ConstraintLayout. Pin each field to the parent start/end and chain them vertically.

3

Create a profile header with an avatar, name, and edit button using RelativeLayout, then refactor it to ConstraintLayout and compare hierarchy depth.

4

Design a product card with an image and a "SALE" badge overlay using FrameLayout and layout_gravity.

5

Build a static pricing table (3 rows: plan name + price) with TableLayout and stretchColumns.

6

Wrap a long registration form (6+ fields) in a ScrollView. Test on a small emulator — confirm all fields scroll into view above the keyboard.

7

Add a layout-sw600dp variant with a two-pane master/detail layout. Show a list on the left and detail on the right for tablet width.

8

Bonus: Create dimens.xml and replace all hard-coded margins/padding in your layouts with dimension resources. Preview in portrait, landscape, and tablet configurations.

Layouts & UI MCQ Practice

10 Basic MCQs 10 Advanced MCQs

10 Basic Layouts & UI MCQs

1

Default recommended layout for complex UIs?

AConstraintLayout
BAbsoluteLayout
CGridLayout only
DNo XML
Explanation: ConstraintLayout flat hierarchy with flexible constraints.
2

LinearLayout arranges children?

AHorizontally or vertically in single line
BRandom positions
COnly overlapping
DIn database
Explanation: orientation vertical|horizontal stacks views.
3

RelativeLayout positions views?

ARelative to siblings or parent
BOnly center always
CUsing SQL
DVia Gradle
Explanation: Rules like below, toRightOf (legacy; ConstraintLayout preferred).
4

ScrollView allows?

ASingle child larger than screen to scroll
BMultiple direct children always
CInfinite RecyclerView
DNative video only
Explanation: ScrollView hosts one child; use NestedScrollView with CoordinatorLayout.
5

match_parent means?

AFill parent container
BWrap content size
C0dp always
DMatch screen diagonal
Explanation: layout_width/height match_parent expands to parent bounds.
6

wrap_content means?

ASize to fit child's content
BFull screen
C50% width
DFixed 100dp always
Explanation: View measures needed space for its content.
7

FrameLayout is useful for?

AStacking overlapping views
BSpreadsheet tables
CNavigation graph
DSQL queries
Explanation: Single-layer stacking — fragments container, progress overlay.
8

TableLayout organizes?

ARows and columns like table
BOnly lists
CServices
DIntents
Explanation: TableRow children define grid-like forms (less common now).
9

layout_weight in LinearLayout?

ADistribute extra space proportionally
BFont weight only
CGradle priority
DAPI level
Explanation: weight sums determine flex space after fixed sizes.
10

0dp in ConstraintLayout width often means?

AMatch constraints (spread between anchors)
BZero pixels visible
CIllegal
Dmatch_parent alias always
Explanation: 0dp (match_constraint) fills space between constrained edges.

10 Advanced Layouts & UI MCQs

11

Barrier in ConstraintLayout?

ADynamic reference line from multiple widgets
BNetwork firewall
CGradle barrier
DPermission wall
Explanation: Barrier adjusts to max/min of referenced views.
12

Guideline used for?

AFixed percentage/offset anchor invisible line
BADB guideline
CLint only
DSigning
Explanation: Guidelines help align without nested layouts.
13

Nested scrolling conflict fix?

ANestedScrollView + RecyclerView nestedScrollingEnabled
BDelete ScrollView always
CUse AbsoluteLayout
DDisable touch
Explanation: Proper nesting or single scrolling parent avoids touch interception.
14

ConstraintLayout chains?

ASpread views horizontally/vertically with bias
BBlockchain
CGradle chain
DIntent chain
Explanation: Chains distribute space packed/spread inside/outside.
15

ViewStub purpose?

ALazy-inflate invisible layout until needed
BReplace Fragment
CDatabase stub
DNetwork stub
Explanation: Inflates layout on setVisibility or inflate — saves memory.
16

merge tag in XML?

AEliminates redundant root when included
BMerges APKs
CCombines modules
DGit merge
Explanation: merge flattens hierarchy when parent is known.
17

include tag?

AReuse layout XML in another layout
BImport Java class
CAdd dependency
DInclude manifest
Explanation: include embeds layout with optional id override.
18

sw600dp qualifier?

ASmallest width tablet bucket
BAPI 600
C600 languages
D600 dpi
Explanation: Alternative layouts for tablets (e.g., two-pane).
19

MotionLayout is?

AConstraintLayout subclass with animations
BAudio layout
CService layout
DGradle script
Explanation: MotionLayout animates constraint changes via MotionScene.
20

RTL layout support requires?

Astart/end margins and layoutDirection awareness
BDisable localization
CEnglish only
DNo ConstraintLayout
Explanation: Use start/end instead of left/right for mirroring in RTL locales.
Click an option to select, then check answers.

Layouts & UI Interview Q&A

15 topic-focused questions for interviews and revision.

1When to use LinearLayout vs ConstraintLayout?easy
Answer: LinearLayout for simple stacks; ConstraintLayout for complex flat UIs with many relationships without deep nesting.
2Explain match_parent vs wrap_content.easy
Answer: match_parent fills parent; wrap_content sizes to content — combine with weights/constraints for flexible UIs.
3Why avoid deep layout hierarchies?medium
Answer: Deep nesting slows measure/layout passes, increases memory, and causes jank — prefer flat ConstraintLayout.
4How does ScrollView limit child count?easy
Answer: One direct child (often a LinearLayout container holding many views).
5ConstraintLayout basics: constraint to parent and widgets.medium
Answer: Connect edges (top, bottom, start, end) to parent or other views with margins; use bias for positioning.
6Responsive UI strategies for phones and tablets.medium
Answer: Alternative layouts (layout-sw600dp), ConstraintLayout percentages, dimens.xml, Compose adaptive navigation.
7What is layout inflation?easy
Answer: Parsing XML layout resource into View objects via LayoutInflater in Activity/Fragment onCreate/setContentView.
8dp vs sp units.easy
Answer: dp density-independent pixels for layout; sp scales with user font preference for text.
9FrameLayout use case with Fragment.medium
Answer: activity_main with FrameLayout or FragmentContainerView hosts NavHost or single Fragment.
10Common ScrollView + EditText issue.medium
Answer: Nested scroll focus; use scrollable container or adjust windowSoftInputMode adjustResize/pan.
11include vs merge performance.medium
Answer: Both reduce duplication; merge avoids extra ViewGroup depth when inflating into known parent.
12TableLayout vs RecyclerView for grids.medium
Answer: RecyclerView preferred for long scrolling grids; TableLayout for small static forms.
13Preview tools attributes (tools:text).easy
Answer: Design-time sample text in editor only — not packaged in APK.
14Accessibility in layouts.medium
Answer: contentDescription for ImageView, sufficient touch targets (48dp), contrast, focus order.
15MotionLayout when to adopt.hard
Answer: Complex gesture-driven UI animations between layout states without manual ObjectAnimator boilerplate.