Layouts & UI
Build flexible Android screens with XML layout managers and responsive design
LinearLayout
ConstraintLayout
ScrollView
Responsive UI
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).
Layout Arrangement When to Use
LinearLayout Single row or column Simple stacked or side-by-side UI
RelativeLayout Relative to siblings or parent Legacy; prefer ConstraintLayout
ConstraintLayout Constraints between views Modern default for complex screens
FrameLayout Stacked (top-left default) Fragments, overlays, single child focus
TableLayout Rows and columns Grid-like data (rare; use RecyclerView for lists)
ScrollView Scrollable container Content taller than the screen
1 LinearLayout
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
Attribute Description
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>
2 RelativeLayout
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
Rule Effect
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
3 ConstraintLayout
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.kts dependencies {
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
Concept Description
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" />
4 FrameLayout
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" />
5 TableLayout
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
Attribute Description
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
6 ScrollView
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
7 Responsive 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
Unit Use For Why
dpPadding, margins, widths, heights Consistent physical size across screen densities
spText size Scales with user's font size accessibility setting
pxAvoid in layouts Pixel-exact but wrong on high-DPI devices
Alternative layout folders
Resource qualifiers for layouts res/
├── 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
8 Hands-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?
A ConstraintLayout
B AbsoluteLayout
C GridLayout only
D No XML
Explanation: ConstraintLayout flat hierarchy with flexible constraints.
2
LinearLayout arranges children?
A Horizontally or vertically in single line
B Random positions
C Only overlapping
D In database
Explanation: orientation vertical|horizontal stacks views.
3
RelativeLayout positions views?
A Relative to siblings or parent
B Only center always
C Using SQL
D Via Gradle
Explanation: Rules like below, toRightOf (legacy; ConstraintLayout preferred).
4
ScrollView allows?
A Single child larger than screen to scroll
B Multiple direct children always
C Infinite RecyclerView
D Native video only
Explanation: ScrollView hosts one child; use NestedScrollView with CoordinatorLayout.
5
match_parent means?
A Fill parent container
B Wrap content size
C 0dp always
D Match screen diagonal
Explanation: layout_width/height match_parent expands to parent bounds.
6
wrap_content means?
A Size to fit child's content
B Full screen
C 50% width
D Fixed 100dp always
Explanation: View measures needed space for its content.
7
FrameLayout is useful for?
A Stacking overlapping views
B Spreadsheet tables
C Navigation graph
D SQL queries
Explanation: Single-layer stacking — fragments container, progress overlay.
8
TableLayout organizes?
A Rows and columns like table
B Only lists
C Services
D Intents
Explanation: TableRow children define grid-like forms (less common now).
9
layout_weight in LinearLayout?
A Distribute extra space proportionally
B Font weight only
C Gradle priority
D API level
Explanation: weight sums determine flex space after fixed sizes.
10
0dp in ConstraintLayout width often means?
A Match constraints (spread between anchors)
B Zero pixels visible
C Illegal
D match_parent alias always
Explanation: 0dp (match_constraint) fills space between constrained edges.
10 Advanced Layouts & UI MCQs
11
Barrier in ConstraintLayout?
A Dynamic reference line from multiple widgets
B Network firewall
C Gradle barrier
D Permission wall
Explanation: Barrier adjusts to max/min of referenced views.
12
Guideline used for?
A Fixed percentage/offset anchor invisible line
B ADB guideline
C Lint only
D Signing
Explanation: Guidelines help align without nested layouts.
13
Nested scrolling conflict fix?
A NestedScrollView + RecyclerView nestedScrollingEnabled
B Delete ScrollView always
C Use AbsoluteLayout
D Disable touch
Explanation: Proper nesting or single scrolling parent avoids touch interception.
14
ConstraintLayout chains?
A Spread views horizontally/vertically with bias
B Blockchain
C Gradle chain
D Intent chain
Explanation: Chains distribute space packed/spread inside/outside.
15
ViewStub purpose?
A Lazy-inflate invisible layout until needed
B Replace Fragment
C Database stub
D Network stub
Explanation: Inflates layout on setVisibility or inflate — saves memory.
16
merge tag in XML?
A Eliminates redundant root when included
B Merges APKs
C Combines modules
D Git merge
Explanation: merge flattens hierarchy when parent is known.
17
include tag?
A Reuse layout XML in another layout
B Import Java class
C Add dependency
D Include manifest
Explanation: include embeds layout with optional id override.
18
sw600dp qualifier?
A Smallest width tablet bucket
B API 600
C 600 languages
D 600 dpi
Explanation: Alternative layouts for tablets (e.g., two-pane).
19
MotionLayout is?
A ConstraintLayout subclass with animations
B Audio layout
C Service layout
D Gradle script
Explanation: MotionLayout animates constraint changes via MotionScene.
20
RTL layout support requires?
A start/end margins and layoutDirection awareness
B Disable localization
C English only
D No ConstraintLayout
Explanation: Use start/end instead of left/right for mirroring in RTL locales.
Check All Answers
Click an option to select, then check answers.
Layouts & UI Interview Q&A
15 topic-focused questions for interviews and revision.
1 When to use LinearLayout vs ConstraintLayout?easy
Answer: LinearLayout for simple stacks; ConstraintLayout for complex flat UIs with many relationships without deep nesting.
2 Explain match_parent vs wrap_content.easy
Answer: match_parent fills parent; wrap_content sizes to content — combine with weights/constraints for flexible UIs.
3 Why avoid deep layout hierarchies?medium
Answer: Deep nesting slows measure/layout passes, increases memory, and causes jank — prefer flat ConstraintLayout.
4 How does ScrollView limit child count?easy
Answer: One direct child (often a LinearLayout container holding many views).
5 ConstraintLayout 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.
6 Responsive UI strategies for phones and tablets.medium
Answer: Alternative layouts (layout-sw600dp), ConstraintLayout percentages, dimens.xml, Compose adaptive navigation.
7 What is layout inflation?easy
Answer: Parsing XML layout resource into View objects via LayoutInflater in Activity/Fragment onCreate/setContentView.
8 dp vs sp units.easy
Answer: dp density-independent pixels for layout; sp scales with user font preference for text.
9 FrameLayout use case with Fragment.medium
Answer: activity_main with FrameLayout or FragmentContainerView hosts NavHost or single Fragment.
10 Common ScrollView + EditText issue.medium
Answer: Nested scroll focus; use scrollable container or adjust windowSoftInputMode adjustResize/pan.
11 include vs merge performance.medium
Answer: Both reduce duplication; merge avoids extra ViewGroup depth when inflating into known parent.
12 TableLayout vs RecyclerView for grids.medium
Answer: RecyclerView preferred for long scrolling grids; TableLayout for small static forms.
13 Preview tools attributes (tools:text).easy
Answer: Design-time sample text in editor only — not packaged in APK.
14 Accessibility in layouts.medium
Answer: contentDescription for ImageView, sufficient touch targets (48dp), contrast, focus order.
15 MotionLayout when to adopt.hard
Answer: Complex gesture-driven UI animations between layout states without manual ObjectAnimator boilerplate.