Courses / Mobile Application Development (CDE-315) – BS CS 5th Semester
Week 7 Theory – Components of a Screen; Adapting to Display Orientation; Managing Changes to Screen Orientation
Week 7 – Screen Components and Orientation · 85 min read · 33 MCQs to check yourself
ConstraintLayout tutorial – layouts in Android XML
Screen rotation: why your activity restarts and how to preserve state
Resources and qualifiers (layout-land, values-sw600dp)
1. Components of a screen
An Android screen (activity) is made of a window that holds a tree (hierarchy) of View and ViewGroup objects.
Window
└── DecorView (status/navigation bar areas, app bar)
└── Content: ConstraintLayout (ViewGroup – root layout)
├── TextView (View)
├── EditText (View)
├── LinearLayout (ViewGroup)
│ ├── Button (View)
│ └── Button (View)
└── ImageView (View)
View
A View is the basic building block of UI: a rectangular area that draws something and handles events (touch, click, keys). All widgets extend android.view.View.
| Widget | Purpose |
|---|---|
| TextView | Displays text |
| EditText | Text input (inputType, hint) |
| Button / ImageButton | Clickable action |
| ImageView | Shows images |
| CheckBox / RadioButton / RadioGroup | Multiple / single choice |
| Switch / ToggleButton | On–off |
| Spinner | Drop-down list |
| ProgressBar / SeekBar | Progress, slider |
| RecyclerView / ListView | Scrolling lists |
| WebView | Web content |
| Material components | MaterialButton, TextInputLayout, FloatingActionButton, Chip, CardView, Snackbar |
ViewGroup
A ViewGroup is an invisible container that holds other views and decides their position and size – all layouts are ViewGroups (LinearLayout, ConstraintLayout, FrameLayout …).
Common View attributes
| Attribute | Meaning |
|---|---|
android:id="@+id/btnSave" |
Unique ID used in code (R.id.btnSave); @+id creates it |
layout_width, layout_height |
match_parent (fill parent), wrap_content (fit content), fixed dp, or 0dp (match constraints) |
margin |
Space outside the view's border |
padding |
Space inside the border, around the content |
gravity |
Alignment of content inside the view |
layout_gravity |
Alignment of the view inside its parent (LinearLayout/FrameLayout) |
visibility |
visible, invisible (hidden but takes space), gone (hidden, no space) |
background, textColor, textSize, hint, inputType |
Appearance and input |
The app bar, status bar and edge-to-edge
The top app bar (Action Bar/Toolbar) shows title and actions (week 8). The status bar and navigation bar belong to the system; from Android 15 apps draw edge-to-edge behind them and use window insets to add padding.
2. Layouts (ViewGroups)
| Layout | How it positions children | Use |
|---|---|---|
| LinearLayout | In a single row or column (orientation), with layout_weight to share space |
Simple forms, toolbars |
| RelativeLayout (legacy) | Relative to parent or siblings (layout_below, alignParentEnd) |
Older apps |
| ConstraintLayout (recommended) | Each view constrained to parent/other views; flat hierarchy, chains, guidelines, bias, percentages | Most screens; responsive designs |
| FrameLayout | Stacks children on top of each other | Single child, fragment containers, overlays |
| TableLayout / GridLayout | Rows and columns | Calculators, grids |
| ScrollView / NestedScrollView | Makes one child scrollable vertically | Long forms |
| CoordinatorLayout | Coordinates scrolling behaviours (app bar collapse, FAB) | Material screens |
LinearLayout weights
<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="Save"/>
</LinearLayout>
"Save" gets two-thirds of the width, "Cancel" one-third.
ConstraintLayout essentials
- Every view needs at least one horizontal and one vertical constraint (e.g.
layout_constraintStart_toStartOf="parent"andlayout_constraintTop_toBottomOf="@id/title"). 0dp(match constraint) fills the space between constraints.- Bias (
layout_constraintHorizontal_bias="0.3"), chains (spread, packed), guidelines (e.g. at 50 %), barriers andlayout_constraintDimensionRatio="16:9". - Flat hierarchy = faster measuring and drawing than deeply nested LinearLayouts.
Layout inflation and the Layout Editor
setContentView(R.layout.x) inflates XML into View objects. Android Studio's Layout Editor offers Design / Split / Code views, the Palette, Component Tree, Attributes panel and Blueprint; the Layout Inspector examines a running app's hierarchy.
3. Screen sizes, densities and units
Screen size and density
- Screen size – physical diagonal (phone 6", tablet 10").
- Resolution – total pixels (1080 × 2400).
- Density (dpi) – pixels per inch.
| Density bucket | dpi | Scale (dp → px) |
|---|---|---|
| ldpi | ~120 | 0.75 × |
| mdpi (baseline) | ~160 | 1 × |
| hdpi | ~240 | 1.5 × |
| xhdpi | ~320 | 2 × |
| xxhdpi | ~480 | 3 × |
| xxxhdpi | ~640 | 4 × |
Formula: px = dp × (dpi ÷ 160) → 48 dp on a 480 dpi phone = 48 × 3 = 144 px.
Units
| Unit | Use |
|---|---|
| dp / dip (density-independent pixel) | Sizes, margins, padding – look the same physical size on all screens |
| sp (scale-independent pixel) | Text – also scales with the user's font-size setting |
| px | Real pixels – avoid (looks different on each density) |
| pt, in, mm | Physical units – rarely used |
Supporting different screens
- Use ConstraintLayout,
wrap_content,match_parent,0dpand weights instead of fixed sizes. - Provide vector drawables (scale perfectly) or bitmaps in
drawable-mdpi/hdpi/xhdpi/xxhdpi/xxxhdpi; launcher icons inmipmap-*. - Window size classes (Compact < 600 dp, Medium 600–840 dp, Expanded > 840 dp) guide layouts for phones, foldables and tablets; Android 16/17 require large-screen apps to resize and support any orientation.
4. Adapting to display orientation
Orientation is either portrait (height > width) or landscape (width > height). Users rotate phones to watch videos, type on wider keyboards or view charts.
Technique 1 – Anchoring / flexible layouts
Design one layout that adapts: constrain views to the edges of the parent (ConstraintLayout), use match_parent/weights so views stretch, and put long content inside a ScrollView so nothing is cut off in landscape.
Technique 2 – Alternative layout resources (resource qualifiers)
Create a second layout with the same file name in a folder with the -land qualifier:
res/layout/activity_main.xml ← portrait (default)
res/layout-land/activity_main.xml ← landscape
Android automatically chooses the matching file when the orientation changes. (Android Studio: in the layout editor click the Orientation icon → Create Landscape Qualifier.) Keep the same view IDs in both files so the code works with either.
Other useful qualifiers: layout-sw600dp (smallest width ≥ 600 dp → tablets), layout-w840dp, values-land/dimens.xml (different margins), values-night (dark theme).
Technique 3 – Detect orientation in code
boolean isLandscape = getResources().getConfiguration().orientation
== Configuration.ORIENTATION_LANDSCAPE;
if (isLandscape) imgBanner.setVisibility(View.GONE);
Or get the display size via WindowMetrics / window size classes.
Technique 4 – Lock the orientation (use sparingly)
<activity android:name=".VideoActivity"
android:screenOrientation="landscape" /> <!-- or "portrait", "sensor", "unspecified" -->
In code: requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT. Note: on large screens (tablets/foldables, ≥ 600 dp) Android 16 and 17 ignore orientation locks for apps targeting those versions – apps must be adaptive.
5. Managing changes to screen orientation
What happens when the device rotates?
Rotation is a configuration change (others: language change, keyboard attached, dark-mode switch, window resize). By default Android destroys the activity and recreates it:
onPause → onStop → onDestroy → onCreate → onStart → onResume (new instance)
This lets the new instance load the correct resources (e.g. layout-land). Problem: variables in the old activity are lost – a counter resets to 0, a downloaded list disappears.
- Views with an ID (EditText text, CheckBox state, scroll position) save their state automatically.
- Your member variables are not saved automatically.
Solution 1 – onSaveInstanceState / Bundle
Save small, simple UI state into a Bundle before destruction and restore it in onCreate (or onRestoreInstanceState):
public class CounterActivity extends AppCompatActivity {
private int count = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_counter);
if (savedInstanceState != null) {
count = savedInstanceState.getInt("COUNT", 0); // restore
}
// ... update the TextView
}
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("COUNT", count); // save
}
}
Bundles are for small data (IDs, text, numbers) – they are serialised and limited (about 1 MB for the whole transaction). They also survive process death (system killing the app in the background).
Solution 2 – ViewModel (recommended by Google)
A ViewModel (Jetpack) stores UI data and survives configuration changes – the same ViewModel object is given to the recreated activity.
public class CounterViewModel extends ViewModel {
public int count = 0;
}
public class CounterActivity extends AppCompatActivity {
private CounterViewModel vm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_counter);
vm = new ViewModelProvider(this).get(CounterViewModel.class); // same object after rotation
TextView tvCount = findViewById(R.id.tvCount);
tvCount.setText(String.valueOf(vm.count));
findViewById(R.id.btnPlus).setOnClickListener(v -> {
vm.count++; // survives rotation
tvCount.setText(String.valueOf(vm.count));
});
}
}
- ViewModel can hold larger data (lists from the network) and use LiveData/StateFlow so the UI observes changes.
- It does not survive process death – combine with SavedStateHandle or
onSaveInstanceStatefor critical state, and a database/SharedPreferences for permanent data.
Solution 3 – Handle the change yourself (android:configChanges)
<activity android:name=".PlayerActivity"
android:configChanges="orientation|screenSize|screenLayout|keyboardHidden" />
The activity is not recreated; instead onConfigurationChanged(newConfig) is called and you must adjust the UI manually. Used for video players, games and camera previews; not recommended in general because alternative resources are no longer applied automatically.
Comparison
| Method | Survives rotation | Survives process death | Data size | Use |
|---|---|---|---|---|
| Views with IDs | Yes (their own state) | Yes | Small | EditText text, checkbox |
| onSaveInstanceState (Bundle) | Yes | Yes | Small (under ~1 MB total) | Counter, selected tab, query text |
| ViewModel | Yes | No (unless SavedStateHandle) | Large | Lists, loaded data |
| configChanges | Activity not recreated | No | Any | Video, games |
| Database / SharedPreferences | Yes | Yes | Any | Permanent data |
Short and long questions
1. List four techniques to adapt the UI to orientation.
Model answer
(1) Flexible/anchored layouts with ConstraintLayout, weights and ScrollView. (2) Alternative resources in layout-land or values-land. (3) Detecting orientation in code with resources.configuration.orientation and adjusting views. (4) Locking orientation with android:screenOrientation (only when necessary).
2. How can an app provide a different layout for landscape orientation?
Model answer
Create a layout file with the same name in res/layout-land (e.g. layout-land/activity_main.xml) using the same view IDs; Android automatically selects it when the device is in landscape.
3. Differentiate between margin and padding, and between gravity and layoutgravity.
Model answer
Margin is space outside a view's border; padding is space inside the border around its content. gravity aligns the content inside a view; layout_gravity aligns the view itself within its parent (LinearLayout/FrameLayout).
4. Differentiate between View and ViewGroup with examples.
Model answer
A View is a single UI element that draws and handles events, e.g. TextView, Button, EditText, ImageView. A ViewGroup is an invisible container that holds Views (and other ViewGroups) and controls their position and size, e.g. LinearLayout, ConstraintLayout, FrameLayout.
5. What are the components of an Android screen? Explain Views, ViewGroups and the main layouts (LinearLayout, ConstraintLayout, FrameLayout, TableLayout, ScrollView) with XML examples and common attributes.
Model answer
An Android screen is a window containing a hierarchy of Views and ViewGroups set by setContentView. A View is a rectangular UI element that draws itself and handles events – TextView, EditText, Button, ImageView, CheckBox, RadioButton, Spinner, ProgressBar, RecyclerView, WebView and Material components. A ViewGroup is a container that arranges children; layouts are ViewGroups.
Common attributes: android:id (@+id/name), layout_width/layout_height (match_parent, wrap_content, dp, 0dp), margin, padding, gravity, layout_gravity, visibility (visible/invisible/gone), text, textSize (sp), hint, inputType, background.
LinearLayout – arranges children in one row or column by orientation; layout_weight divides extra space (two buttons with width 0dp and weights 1 and 2).
ConstraintLayout – each view is positioned by constraints to the parent or siblings (layout_constraintTop_toBottomOf="@id/title"), with 0dp match-constraint sizes, bias, chains, guidelines and dimension ratios; it creates flat, responsive and fast layouts and is the default in Android Studio.
FrameLayout – stacks children; used for single views, overlays and fragment containers.
TableLayout/GridLayout – rows and columns, e.g. calculator keypads.
ScrollView – wraps one child to make long content scroll; needed so forms are not cut off in landscape.
Others: RelativeLayout (legacy), CoordinatorLayout (Material scrolling behaviour).
Example: a ConstraintLayout containing a TextView constrained to the top and a Button constrained below it and centred horizontally. Good practice: keep hierarchies flat, use dp/sp, avoid fixed pixel sizes, and design with the Layout Editor and Layout Inspector.
6. Name five Android layouts and their use.
Model answer
LinearLayout – children in one row/column; ConstraintLayout – flexible flat layouts with constraints (recommended); FrameLayout – stacked children/containers; TableLayout/GridLayout – rows and columns; ScrollView – scrolling content (also RelativeLayout, CoordinatorLayout).
7. Differentiate between dp, sp and px. Convert 24 dp to px on an xhdpi device.
Model answer
px are physical pixels; dp are density-independent pixels (1 dp = 1 px at 160 dpi) for sizes; sp are like dp but also scale with the user's font size, used for text. On xhdpi (320 dpi): px = 24 × 320/160 = 48 px.
8. Compare onSaveInstanceState and ViewModel for preserving state.
Model answer
onSaveInstanceState stores small, serialisable UI state in a Bundle that survives rotation and process death. A ViewModel keeps larger UI data in memory and survives configuration changes but not process death, unless combined with SavedStateHandle. Permanent data should go to a database or SharedPreferences.
9. What happens to an activity when the screen is rotated?
Model answer
Rotation is a configuration change; by default the activity is destroyed (onPause, onStop, onDestroy) and a new instance is created (onCreate, onStart, onResume) so it can load resources for the new orientation. Unsaved member variables are lost.
10. How does Android handle screen orientation changes? Explain the problem of losing data on rotation and describe the techniques to adapt to and manage orientation changes, with code.
Model answer
Adapting: apps should work in portrait and landscape by (1) flexible layouts – ConstraintLayout anchored to edges, weights, match_parent/0dp, ScrollView; (2) alternative resources – a layout with the same name in res/layout-land (and layout-sw600dp for tablets, values-land for dimensions) chosen automatically; (3) checking resources.configuration.orientation in code to show/hide views; (4) locking orientation with android:screenOrientation only when essential (ignored on large screens by Android 16/17-targeting apps).
What happens on rotation: orientation is a configuration change, so Android destroys the activity (onPause → onStop → onDestroy) and recreates it (onCreate → onStart → onResume) to load the right resources. Views with IDs restore their own state, but member variables (a counter, a downloaded list) are lost.
Managing state:
- onSaveInstanceState(outState) – put small values in the Bundle (
outState.putInt("COUNT", count)) and restore in onCreate (if (savedInstanceState != null) count = savedInstanceState.getInt("COUNT", 0);). Survives rotation and process death; limited size. - ViewModel –
vm = new ViewModelProvider(this).get(CounterViewModel.class);; data in the ViewModel survives recreation and can be observed with LiveData; add SavedStateHandle for process death. - android:configChanges="orientation|screenSize" – the activity is not recreated; onConfigurationChanged(newConfig) is called and the developer updates the UI manually (video players, games). Not recommended generally because alternative resources are not reloaded.
- Persistent storage – SharedPreferences, files or a Room database for data that must survive app restarts.
Choosing correctly prevents lost input, repeated network calls and crashes when users rotate devices.
This lesson ends with a quiz of 33 MCQs. Open the lesson on PrepOasis to take it and save your progress.
Previous: Week 6 Lab 6 – Open the Browser and the Dialer Using Buttons (plus a notification bonus) · Next: Week 7 Lab 7 – Design a Registration Form Using TextView, EditText, Button and RadioButton
All lessons in Mobile Application Development (CDE-315) – BS CS 5th Semester