Android Lock Screen While Playing Games

Support for different screen sizes enables the greatest number of users and widest diversity of devices to admission your app.

To support every bit many screen sizes as possible, design your app layouts to exist responsive and adaptive. Responsive/adaptive layouts provide an optimized user experience regardless of screen size, enabling your app to conform phones, tablets, foldable and Chrome OS devices, portrait and landscape orientations, and resizable configurations such equally multi-window style.

Window size classes

Window size classes are a gear up of opinionated viewport breakpoints that assist you design, develop, and test responsive and adaptive application layouts. The breakpoints have been chosen specifically to residue layout simplicity with the flexibility to optimize your app for unique cases.

Window size classes categorize the display area bachelor to your app as
compact,
medium, or
expanded. Bachelor width and height are classified separately, so at any bespeak in fourth dimension, your app has 2 window size classes—one for width, one for height. Available width is ordinarily more of import than available height due to the ubiquity of vertical scrolling, so the width window size form will likely be more relevant to your app’s UI.

Figure ane.
Representations of width-based window size classes.
Figure 2.
Representations of elevation-based window size classes.

Every bit visualized above, the breakpoints allow you to continue thinking about layouts in terms of devices and configurations. Each size class breakpoint represents a bulk case for typical device scenarios, which can exist a helpful frame of reference as you lot think about the design of your breakpoint-based layouts.

Size class Breakpoint Device representation
Compact width width < 600dp 99.96% of phones in portrait
Medium width 600dp ≤ width < 840dp 93.73% of tablets in portrait,

Large unfolded inner displays in portrait

Expanded width width ≥ 840dp 97.22% of tablets in landscape,

Large unfolded inner displays in landscape

Meaty pinnacle height < 480dp 99.78% of phones in landscape
Medium peak 480dp ≤ height < 900dp 96.56% of tablets in landscape,

97.59% of phones in portrait

Expanded height height ≥ 900dp 94.25% of tablets in portrait

Although it tin can exist useful to visualize size classes as physical devices, window size classes are explicitly not determined by the size of the device screen. Window size classes are not intended for
isTablet-type logic. Rather, window size classes are determined by the window size available to your application regardless of the type of device the app is running on, which has two important consequences:

  • Physical devices practice non guarantee a specific window size grade.
    The screen space available to your app tin can differ from the screen size of the device for many reasons. On mobile devices, split‑screen mode can sectionalization the screen between two applications. On Chrome Bone, Android apps can be presented in free‑form windows that are arbitrarily resizable. Foldables can take two different-sized screens individually accessed by folding or unfolding the device.

  • The window size form tin change throughout the lifetime of your app.
    While your app is running, device orientation changes, multitasking, and folding/unfolding tin can change the amount of screen infinite available. Equally a result, the window size grade is dynamic, and your app’s UI should adjust accordingly.

Window size classes map to the layout breakpoints in the Material Design responsive layout grid. Use window size classes to brand high-level application layout decisions, such as deciding whether to use a specific approved layout to take advantage of additional screen space.

View-based apps should calculate the window size grade based on the current window metrics provided by the Jetpack WindowManager library. The example lawmaking beneath in
Views Kotlin
and
Views Java
shows an example of how to calculate the window size class based on the breakpoints and receive updates whenever it changes.

Compose-based apps should use the
material3-window-size-class
library to calculate a
WindowSizeClass
based on the current window metrics with
calculateWindowSizeClass().

Views

enum course WindowSizeClass { Compact, MEDIUM, EXPANDED }  class MainActivity : Activity() {     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)          // ...          // Supplant with a known container that y'all can safely add a         // view to where it won't touch on the layout and the view         // won't be replaced.         val container: ViewGroup = bounden.container          // Add a utility view to the container to claw into         // View.onConfigurationChanged. This is required for all         // activities, fifty-fifty those that don't handle configuration         // changes. Nosotros likewise can't apply Activity.onConfigurationChanged,         // since there are situations where that won't be called when         // the configuration changes. View.onConfigurationChanged is         // called in those scenarios.         container.addView(object : View(this) {             override fun onConfigurationChanged(newConfig: Configuration?) {                 super.onConfigurationChanged(newConfig)                 computeWindowSizeClasses()             }         })          computeWindowSizeClasses()     }      individual fun computeWindowSizeClasses() {         val metrics = WindowMetricsCalculator.getOrCreate()             .computeCurrentWindowMetrics(this)          val widthDp = metrics.premises.width() /             resources.displayMetrics.density         val widthWindowSizeClass = when {             widthDp < 600f -> WindowSizeClass.Meaty             widthDp < 840f -> WindowSizeClass.MEDIUM             else -> WindowSizeClass.EXPANDED         }          val heightDp = metrics.bounds.elevation() /             resource.displayMetrics.density         val heightWindowSizeClass = when {             heightDp < 480f -> WindowSizeClass.Meaty             heightDp < 900f -> WindowSizeClass.MEDIUM             else -> WindowSizeClass.EXPANDED         }          // Use widthWindowSizeClass and heightWindowSizeClass.     } }
          

Views

public enum WindowSizeClass { COMPACT, MEDIUM, EXPANDED }  public grade MainActivity extends Activity {     @Override     protected void onCreate(Packet savedInstanceState) {         super.onCreate(savedInstanceState);          // ...          // Supercede with a known container that you tin can safely add a         // view to where it won't impact the layout and the view         // won't be replaced.         ViewGroup container = binding.container;          // Add a utility view to the container to hook into         // View.onConfigurationChanged. This is required for all         // activities, even those that don't handle configuration         // changes. We besides can't use Activity.onConfigurationChanged,         // since there are situations where that won't be called when         // the configuration changes. View.onConfigurationChanged is         // called in those scenarios.         container.addView(new View(this) {             @Override             protected void onConfigurationChanged(Configuration newConfig) {                 super.onConfigurationChanged(newConfig);                 computeWindowSizeClasses();             }         });          computeWindowSizeClasses();     }      individual void computeWindowSizeClasses() {         WindowMetrics metrics = WindowMetricsCalculator.getOrCreate()                 .computeCurrentWindowMetrics(this);          float widthDp = metrics.getBounds().width() /                 getResources().getDisplayMetrics().density;         WindowSizeClass widthWindowSizeClass;          if (widthDp < 600f) {             widthWindowSizeClass = WindowSizeClass.COMPACT;         } else if (widthDp < 840f) {             widthWindowSizeClass = WindowSizeClass.MEDIUM;         } else {             widthWindowSizeClass = WindowSizeClass.EXPANDED;         }          float heightDp = metrics.getBounds().height() /                 getResources().getDisplayMetrics().density;         WindowSizeClass heightWindowSizeClass;          if (heightDp < 480f) {             heightWindowSizeClass = WindowSizeClass.COMPACT;         } else if (heightDp < 900f) {             heightWindowSizeClass = WindowSizeClass.MEDIUM;         } else {             heightWindowSizeClass = WindowSizeClass.EXPANDED;         }          // Apply widthWindowSizeClass and heightWindowSizeClass.     } }
          

Compose

form MainActivity : ComponentActivity() {     override fun onCreate(savedInstanceState: Parcel?) {         super.onCreate(savedInstanceState)          setContent {             val windowSizeClass = calculateWindowSizeClass(this)             MyApp(windowSizeClass)         }     } }
          

Once you lot’re observing window size classes in your app, y’all’re ready to start changing your layout based on the current window size class.

To learn how to use window size classes to make layouts responsive, see the following:

  • For view-based layouts, Migrate your UI to responsive layouts
  • For Compose-based layouts, Build adaptive layouts

Checklist for supporting different window size classes

As you lot make layout changes, test the layout beliefs across all ranges of window sizes, specially at the compact, medium, and expanded breakpoint widths.

If y’all accept an existing layout for compact screens, first optimize your layout for the expanded width size class, as this provides the nigh space for additional content and UI changes. Then make up one’s mind what layout makes sense for the medium width size class. Consider adding a specialized layout for the medium width screen size.

Provide an enhanced user experience by calculation functionality that applies specifically to your app, such as back up for foldable postures or optimizations for keyboard, mouse, and stylus input support.

To learn more virtually what makes an app great across all devices and screen sizes, see Large screen app quality.

Responsive design

The first pace in supporting a multifariousness of device class factors is to create a layout that is responsive to variations in screen size.

ConstraintLayout

The all-time manner to create a responsive layout is to use
ConstraintLayout
as the base layout in your UI.
ConstraintLayout
enables yous to specify the position and size of each view co-ordinate to spatial relationships with other views in the layout. All the views can so motion and resize together as the screen size changes.

The easiest way to build a layout with
ConstraintLayout
is to use the Layout Editor in Android Studio. Layout Editor enables you to elevate new views to the layout, employ constraints relative to parent and sibling views, and set view backdrop—all without editing any XML by manus.

Figure three.
The Layout Editor in Android Studio showing a
ConstraintLayout.

For more information, see Build a Responsive UI With ConstraintLayout.

Responsive width and superlative

To ensure that your layout is responsive to different screen sizes, use
wrap_content,
match_parent, or
0dp (match constraint)
for the width and acme of near view components instead of difficult-coded values:

  • wrap_content
    — Enables the view to ready its size to whatever is necessary to fit the content contained in the view.
  • match_parent
    — Enables the view to expand every bit much every bit possible inside the parent view.
  • 0dp (match constraint)
    — In a
    ConstraintLayout, like to
    match_parent. Enables the view to take all the available space inside the view’south constraints.

For example:

        <TextView     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:text="@string/lorem_ipsum" />
        
      

Figure iv shows how the width and height of the
TextView
adjust as the screen width changes with device orientation.

Figure 4.
A responsive
TextView.

The
TextView
sets its width to fill all available infinite (match_parent) and set its acme to exactly equally much space is required past the height of the contained text (wrap_content), which enables the view to suit to different screen sizes and unlike amounts of text.

If you’re using a
LinearLayout, y’all can also expand the child views based on layout weight so that the views proportionally fill the bachelor infinite. However, using weights in a nested
LinearLayout
requires the system to perform multiple layout passes to determine the size for each view, slowing UI functioning.

ConstraintLayout
can create nearly all of the layouts possible with
LinearLayout
without the performance impact, so you should try converting your nested
LinearLayout
to
ConstraintLayout. And then y’all can define weighted layouts with constraint chains.

Adaptive design

Your app’southward layout should e’er exist responsive to unlike screen sizes. However, even a responsive layout tin can’t provide the best user experience on every device. For example, the UI you lot designed for a phone, probably doesn’t provide an optimal experience on a tablet. Adaptive design provides alternative layouts optimized for different display dimensions.

SlidingPaneLayout for listing-item UIs

A list-detail UI typically provides a different user experience on different-size screens. On large screens, the list and detail panes are usually adjacent. When an item in the list is selected, item information is displayed in the detail pane without changing the UI—the 2 panes remain adjacent. All the same, on small screens, the two panes are displayed separately, each pane occupying the entire display area. When an particular in the listing pane is selected, the detail pane (containing the selected particular’s information) replaces the list pane. Dorsum navigation replaces the detail pane with the list.

SlidingPaneLayout
manages the logic for determining which of the two user experiences is advisable for the current window size:

        <?xml version="i.0" encoding="utf-viii"?> <androidx.slidingpanelayout.widget.SlidingPaneLayout     xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-automobile"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context=".MainActivity">      <androidx.recyclerview.widget.RecyclerView         android:id="@+id/recycler_view"         android:layout_width="280dp"         android:layout_height="match_parent"         android:layout_gravity="start" />      <androidx.fragment.app.FragmentContainerView         android:id="@+id/nav_host_fragment"         android:name="androidx.navigation.fragment.NavHostFragment"         android:layout_width="300dp"         android:layout_height="match_parent"         android:layout_weight="one"         app:defaultNavHost="true"         app:navGraph="@navigation/item_navigation" />  </androidx.slidingpanelayout.widget.SlidingPaneLayout>
        
      

The
layout_width
and
layout_weight
attributes of the two views contained in
SlidingPaneLayout
determine the
SlidingPaneLayout
behavior. In the example, if the window is big plenty (at least 580dp wide) to display both views, the panes are displayed side by side. But, if the window width is smaller than 580dp, the panes slide over ane another to individually occupy the entire app window.

If the window width is larger than the total specified minimum width (580dp),
layout_weight
values can be used to size the two panes proportionally. In the case, the list pane is always 280dp wide considering it does non have a weight. The detail pane however, always fills any horizontal space beyond 580dp because of the view’south
layout_weight.

Culling layout resources

To adapt your UI design to widely varying screen sizes, apply alternative layouts identified by resource qualifiers.

Effigy 5.
The aforementioned app on dissimilar screen sizes using a different layout for each.

You can provide adaptive, screen-specific layouts by creating additional
res/layout/
directories in your app’s source code. Create a directory for each screen configuration that requires a different layout. Then append a screen configuration qualifier to the
layout
directory name (for example,
layout-w600dp
for screens that have 600dp of available width).

The configuration qualifiers represent the visible screen space available for your app UI. The arrangement takes into account any system decorations (such equally the navigation bar) and window configuration changes (such as multi-window mode) when selecting the layout for your app.

To create an culling layout in Android Studio (using version 3.0 or higher), practice the post-obit:

  1. Open your default layout and then click
    Orientation for Preview

    in the toolbar.
  2. In the drop-down list, click to create a suggested variant such as
    Create Landscape Variation, or click
    Create Other.
  3. If yous selected
    Create Other, the
    Select Resource Directory
    appears. Select a screen qualifier on the left and add it to the list of
    Called qualifiers. When you’re done adding qualifiers, click
    OK. (Come across the post-obit sections for data about screen size qualifiers.)

A duplicate of your default layout file is created in the new layout directory so you can begin customizing the layout for that screen variant.

Smallest width qualifier

The
smallest width
screen size qualifier enables you to provide alternative layouts for screens that have a minimum width measured in density-independent pixels (dp or dip).

Past describing the screen size as a measure of dp, Android enables you to create layouts that are designed for specific screen dimensions without concern for unlike pixel densities.

For example, you tin create a layout named
main_activity
that’s optimized for phones and tablets past creating unlike versions of the file in different directories:

res/layout/main_activity.xml           # For phones (smaller than 600dp smallest width) res/layout-sw600dp/main_activity.xml   # For 7” tablets (600dp wide or wider)
      

The
smallest width
qualifier specifies the smallest of the screen’s ii sides, regardless of the device’s current orientation, so it’due south a elementary mode to specify the overall screen size bachelor for your layout.

Here’due south how other smallest width values correspond to typical screen sizes:

  • 320dp: Typical phone screen (240×320 ldpi, 320×480 mdpi, 480×800 hdpi, etc.)
  • 480dp: Large phone screen ~5″ (480×800 mdpi)
  • 600dp: seven” tablet (600×1024 mdpi)
  • 720dp: 10” tablet (720×1280 mdpi, 800×1280 mdpi, etc.)

Figure six provides a more detailed view of how different screen dp widths generally correspond to unlike screen sizes and orientations.

Figure vi.
Recommended width breakpoints to back up dissimilar screen sizes.

Values for the
smallest width
qualifier are dp, because what matters is the amount of screen space available later the system accounts for pixel density (non the raw pixel resolution).

The sizes yous specify using resource qualifiers similar
smallest width
are
not the actual screen sizes. Rather, the sizes specify the width or superlative in dp units that are
available to your app’southward window. The Android system might use some of the screen for organization UI (such as the system bar at the lesser of the screen or the condition bar at the top), and then some of the screen might not be bachelor for your layout. If your app is used in multi-window style, the app only has access to the size of the window that contains the app. When the window is resized, information technology triggers a configuration alter with the new window size, which enables the system to select an appropriate layout file. So, the resource qualifier sizes yous declare should specify only the space needed past your app. The system accounts for whatever space used by system UI when providing space for your layout.

Available width qualifier

Instead of changing the layout based on the smallest width of the screen, yous might want to modify your layout based on how much width or peak is currently bachelor. For example, you might desire to use a 2-pane layout whenever the screen provides at least 600dp of width, which might change depending on whether the device is in landscape or portrait orientation. In that example, you should use the
available width
qualifier as follows:

res/layout/main_activity.xml         # For phones (smaller than 600dp available width) res/layout-w600dp/main_activity.xml  # For vii” tablets or any screen with 600dp available width                                      # (maybe landscape phones)
      

If available height is a concern for your app, yous tin can use the
bachelor elevation
qualifier. For case,
layout-h600dp
for screens with at least 600dp of screen acme.

Orientation qualifiers

Even though you may be able to support all size variations using only combinations of the
smallest width
and
bachelor width
qualifiers, you might also desire to change the user experience when the user switches between portrait and landscape orientations.

For that, yous can add the
port
or
country
qualifiers to your layout directory names. Merely be sure the orientation qualifiers come later on the size qualifiers. For example:

res/layout/main_activity.xml                # For phones res/layout-country/main_activity.xml           # For phones in mural res/layout-sw600dp/main_activity.xml        # For 7” tablets res/layout-sw600dp-land/main_activity.xml   # For seven” tablets in mural
      

For more information about all the screen configuration qualifiers, come across App resources overview.

Modularized UI components using fragments

When designing your app for multiple screen sizes, employ fragments to extract your UI logic into separate components to make sure you lot aren’t needlessly duplicating UI behavior across activities. Then you can combine fragments to create multi-pane layouts on large screens, or you lot can place fragments in separate activities on small screens.

For example, the list-particular pattern (see SlidingPaneLayout above) could exist implemented with 1 fragment containing the list and another fragment containing the listing item details. On big screens the fragments could be displayed side past side; on pocket-size screens, individually, filling the screen.

To larn more, see the Fragments overview.

Activity embedding

If your app consists of multiple activities, activeness embedding enables yous to hands create an adaptive UI.

Activity embedding displays multiple activities or multiple instances of the same activity simultaneously in an awarding’s chore window. On big screens, activities tin can be displayed next; on small screens, stacked one on height of the other.

You determine how your app displays its activities by creating an XML configuration file which the system uses to determine the advisable presentation based on screen size. Alternatively, you can make Jetpack WindowManager API calls.

Action embedding supports device orientation changes and foldable devices, stacking and unstacking activities every bit the device rotates or folds and unfolds.

For more information, meet Activity embedding.

Screen sizes and aspect ratios

Test your app on a multifariousness of screen sizes and aspect ratios to ensure your UI scales correctly.

Android 10 (API level 29) and higher support a wide range of attribute ratios. Foldable course factors tin vary from tall, narrow screens, such every bit 21:9 when folded, to a square aspect ratio of one:ane when unfolded.

To ensure compatibility with every bit many devices as possible, examination your apps for equally many of the following screen aspect ratios as you can.

Figure 7.
Screen aspect ratios.

If you cannot back up some attribute ratios, use
maxAspectRatio
and
minAspectRatio
to indicate the highest and lowest ratios your app tin can handle. In cases where screens exceed these limits, your app might be put in compatibility mode.

If you lot don’t have access to devices for all the dissimilar screen sizes you want to test, you can use the Android Emulator to emulate virtually any screen size.

If you lot would rather test on a existent device only don’t have the device, you can use the Firebase Test Lab to access devices in a Google information center.

Specific screen size back up

If yous decide that yous don’t want your app to run at certain screen sizes, y’all can set limits for how much your app should resize, or you tin can even restrict which devices can install your app based on screen configuration. For more information, see Declare restricted screen back up.

Additional resources

  • Adaptive design

Source: https://developer.android.com/guide/topics/large-screens/support-different-screen-sizes