Quantcast
Jump to content


Craft Adaptable UI for Android Applications Using Jetpack Compose


Recommended Posts

2024-07-25-01-banner.jpg

In the dynamic landscape of mobile technology, the introduction of the Jetpack Compose toolkit has opened a lot of opportunities for developers to create beautiful, seamless applications using declarative UI. Using this new model of UI development, developers can create adaptable applications targeting a wide range of mobile devices.

In this post, we learn how to integrate Android's new adaptive library into a pre-built compose application and leverage its APIs to create a dynamic user interface.

Overview of the application

undefined
undefined
undefined
undefined

Figure 1: Application UI on the Galaxy Z Flip5

undefined

The example application is a simple list of mobile devices for sale. It is built using an ElevatedCard composable that is displayed by a LazyVerticalGrid composable. Each card is modeled after a data class named Mobile. Let’s take a look at the data class and composable functions below:

/// Data class to hold Mobile data
data class Mobile(
    @StringRes val name: Int,
    @DrawableRes val photoId: Int,
    val price: String
)
/// MainActivity.kt

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ComposeAppTheme {
                MyApp()
            }
        }
    }
}

@Composable
fun MyApp(){
    Surface(
        modifier = Modifier
            .fillMaxSize()
            .statusBarsPadding(),
        color = MaterialTheme.colorScheme.background
    ) {
        MobileGrid(
            modifier = Modifier.padding(
                start = 8.dp,
                top = 8.dp,
                end = 8.dp,
            )
        )
    }
}

@Composable
fun MobileGrid(modifier: Modifier = Modifier){
    LazyVerticalGrid(
        columns = GridCells.Fixed(2),
        verticalArrangement = Arrangement.spacedBy(8.dp),
        horizontalArrangement = Arrangement.spacedBy(8.dp),
        modifier = modifier
    ) {
        items(MobileDataSource.mobiles) { mobile ->
            MobileCard(mobile)
        }
    }
}

@Composable
fun MobileCard(mobile: Mobile, modifier: Modifier=Modifier){
    ElevatedCard() {
        Row {
            Image(
                painter = painterResource(id = mobile.photoId),
                contentDescription = null,
                modifier = modifier
                    .size(width = 68.dp, height = 68.dp),
                contentScale = ContentScale.Crop
            )
            Column(
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                Text(
                    text = stringResource(id = mobile.name),
                    modifier = Modifier.padding(
                        start = 16.dp,
                        top = 16.dp,
                        end = 16.dp,
                    ),
                    style = MaterialTheme.typography.labelLarge,
                )
                Text(
                    text = mobile.price,
                    style = MaterialTheme.typography.labelSmall,
                )
            }
        }
    }
}

As we’ve seen, the application UI looks good on the Samsung Galaxy Z Flip5. But how does it look on the Galaxy Z Fold5?

undefined
undefined
undefined
undefined

Figure 2: Application UI on the Galaxy Z Fold5

undefined

On the Galaxy Z Fold5, the cards are now very stretched and contain a lot of blank space. The unfolded state of foldable devices has a larger screen size and it is important to keep large screens in mind when developing your application. Otherwise, the application may look great on conventional mobile devices, but very off putting on larger devices such as tablets, foldables, and so on.

Create an adaptive layout for your application

The material-3 adaptive library provides some top-level functions that we can leverage to adapt our applications to different form factors. We will use the currentWindowAdaptiveInfo() function to retrieve the WindowSizeClass. The WindowSizeClass allows us to catch breakpoints in the viewport and change the application UI for different form factors. Follow the steps below to change the application's appearance depending on the screen size.

  1. Add the following dependencies to the app-level build.grade file
     ...
     implementation "androidx.compose.material3.adaptive:adaptive:1.0.0-beta04"
     ...
    

  2. Create a variable called windowSizeClass to store the WindowSizeClass from currentWindowAdaptiveInfo() in the MobileGrid() composable. It contains a member variable named widthSizeClass that is a type of WindowWidthSizeClass. The possible values of this class are Compact, Medium, and Expanded. We will use this value to change the layout of the application. Create a new variable named numberOfColumns to dynamically set the number of grid columns in the MobileGrid() composable depending on the width of the screen.
    fun MobileGrid(modifier: Modifier = Modifier){
        val windowSizeClass = currentWindowAdaptiveInfo().windowSizeClass
        val numberOfColumns: Int = when(windowSizeClass.windowWidthSizeClass) {
        WindowWidthSizeClass.COMPACT -> 2
        WindowWidthSizeClass.MEDIUM -> 3
        else -> 4
    }
    
        LazyVerticalGrid(
            modifier = modifier,
            columns = GridCells.Fixed(numberOfColumns),
            verticalArrangement = Arrangement.spacedBy(8.dp),
            horizontalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            items(MobileDataSource.mobiles) { mobile ->
                MobileCard(mobile)
            }
        }
    }
    

That's all! Your application now has a seamless, responsive UI that changes based on the size of the screen it is being displayed on. Let's see what it looks like now on the Galaxy Z Fold5.

undefined
undefined
undefined
undefined

Figure 3: Updated UI on the Galaxy Z Fold5

undefined

Add support for pop-up view

Android enables users to improve their efficiency by leveraging its multi-tasking features. More than half of foldable users use the split-screen, multi window, or pop-up modes daily, so it is imperative that modern applications integrate support for these viewing modes. Let's have a look at the UI in pop-up mode.

undefined
undefined
undefined
undefined

Figure 4: UI on the Galaxy Z Fold5 - pop-up mode

undefined

As you can see, the UI is completely broken in pop-up mode. The mode has a much smaller viewport width and height, so it'd be better to display just 1 column of tiles. We can do this by using the currentWindowSize() function from the adaptive library that uses the WindowMetrics class to calculate the width and height of the viewport. Create a variable named currentWindowWidthSize and retrieve the window width size using the function. If the viewport width is too low, less than 800 pixels in the example below, we can set the numberOfColumns variable to 1.

@Composable
    fun MobileGrid(modifier: Modifier = Modifier){
        val windowSizeClass = currentWindowAdaptiveInfo().windowSizeClass
        val currentWindowWidthSize = currentWindowSize().width
        val numberOfColumns: Int = when(windowSizeClass.windowWidthSizeClass) {
            WindowWidthSizeClass.COMPACT -> {
                if(currentWindowWidthSize < 800) 1 else 2
            }
            WindowWidthSizeClass.MEDIUM -> 3
            else -> 4
        }

        LazyVerticalGrid(
            modifier = modifier,
            columns = GridCells.Fixed(numberOfColumns),
            verticalArrangement = Arrangement.spacedBy(8.dp),
            horizontalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            items(MobileDataSource.mobiles) { mobile ->
                MobileCard(mobile)
            }
        }
    }
undefined
undefined
undefined
undefined

Figure 5: Updated UI on the Galaxy Z Fold5 - pop-up mode

undefined

Conclusion

You have now successfully used the new material-3 adaptive library to change the layout of your application to support foldables and large screen devices in portrait, landscape, split-screen or pop-up modes. By leveraging Jetpack Compose and Android APIs, you can create a consistent and optimized user experience across various screen sizes and device types. If you are interested in developing adaptive applications in XML, check out the links in the section below.

View the full blog at its source

Link to comment
Share on other sites



  • Replies 0
  • Created
  • Last Reply

Top Posters In This Topic

Popular Days

Top Posters In This Topic

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
  • Similar Topics

    • By Samsung Newsroom
      Samsung Electronics today announced the launch of its latest innovations in home entertainment, The Premiere 9 and The Premiere 7. These ultra-short throw projectors, designed to deliver an unparalleled viewing experience, transform any living space into a premium home cinema with stunning 4K resolution, immersive audio and other advanced features.
       
      “The Premiere lineup is set to redefine the premium home cinema experience by combining our advanced laser technology with cutting-edge, user-friendly features that offer stunning picture quality and immersive sound,” said Cheolgi Kim, Executive Vice President of Visual Display Business at Samsung Electronics. “As we continue to innovate, we envision a future where our products transform everyday living spaces into immersive entertainment hubs, setting new standards for home entertainment.”
       
       
      Unmatched Picture and Sound Quality
      Samsung’s newest entries in The Premiere lineup meet the growing demand for high-quality entertainment solutions, using cutting-edge laser technology to bring the cinema experience directly to homes. The Premiere 9 features triple laser technology for enhanced color accuracy and brightness, while both models offer ultra-short throw capabilities and vibrant 4K resolution on screens up to 130 inches.1
       
      The Premiere’s vibrant 4K resolution and exceptional color accuracy bring every scene to life. The Premiere 9 and The Premiere 7 projectors provide color gamut coverage of 154% and 100% of the DCI-P3 standard,2 respectively, while both models support HDR10+, ensuring clear and vivid images — even in bright environments. With a maximum brightness of 3,450 ISO lumens3 for The Premiere 9 and 2,500 ISO lumens for The Premiere 7, these projectors both deliver sharp and dynamic visuals.4
       
      To further enhance picture quality, The Premiere projectors are equipped with innovative AI picture enhancements, including AI Upscaling and Vision Booster. AI Upscaling ensures that content is displayed in stunning 4K resolution, regardless of its original quality, while Vision Booster automatically adjusts brightness and contrast in various lighting conditions for optimal picture quality.
       
      The built-in speakers with Dolby Atmos technology in both models provide powerful and immersive audio, creating a true home theater experience without the need for additional sound equipment. The Premiere 9 features 40W 2.2.2 channel up-firing speakers, while The Premiere 7 includes 30W 2.2ch speakers for an expansive dome of sound.
       

       
       
      Samsung Tizen OS Home Brings Streaming and Gaming, Along With Broad Connectivity
      The new Premiere projectors come with Samsung Tizen OS Home, offering access to a wide range of streaming services, including Samsung TV Plus, Netflix, YouTube, Amazon Prime Video and more. This extensive selection ensures that users can enjoy their favorite movies, TV shows, providing a comprehensive entertainment experience at the click of a button.
       
      For gaming enthusiasts, the Samsung Gaming Hub5 offers a seamless gaming experience. Users can enjoy games without the need for a console, accessing a wide choice of cloud-based games directly through the projector.
       
      For those who want to create a tailor-made interior, Custom Ambient offers personalized home decorations by projecting various widgets onto the living space. Users can combine photos, videos and widgets freely via the SmartThings app on their mobile phones.
       
      Even when not being used as a fully cinematic projector, The Premiere ensures convenience and entertainment for all consumers as a Smart speaker with hands-free voice control and a variety of music applications.
       
      The new Premiere projectors also enhance connectivity, providing a seamless and integrated entertainment experience. Users can effortlessly share content from their smartphones to the big screen with Tap View and Mirroring, while embedded voice assistant support allows easy control of the projector and other connected devices with simple voice commands. Additionally, Samsung’s SmartThings integration enables users to manage smart home devices such as lights, thermostats and security systems from the projector, thereby creating a fully integrated home environment.
       

       
       
      A Design Fit for Any Home Environment
      The Premiere projectors feature a minimalist, warm white design with rounded edges and a premium fabric finish from Kvadrat, a Danish textile design company that seamlessly blends in with any home decor. The compact size and easy installation make the projectors an ideal fit for any room, maximizing both functionality and aesthetic appeal.
       
      Setting up any model of The Premiere is simple — users merely need to plug in the projector and connect to a wireless network. Ultra-short throw capabilities eliminate the need for complex installations, allowing users to enjoy large-screen projections with minimal effort.
       
      The new Premiere 9 and Premiere 7 projectors are now available for purchase at Samsung’s official online store and select retail locations in the United States, Canada and China. The rollout will continue in other regions later this year. For more information, please visit Samsung.com.
       
       
      1 The Premiere 7 provides 4K high resolution on screens up to 120 inches.
      2 DCI-P3, known as Digital Cinema Initiatives – Protocol 3, is a color space commonly used in digital cinema and is the color standard for the film industry.
      3 ISO lumens is the brightness level based on the International Organization for Standardization (ISO) standards.
      4 The brightness levels for The Premiere 9 (3,450 ISO lumens) and The Premiere 7 (2,500 ISO lumens) reflect approximate increases of 23% and 14% over previous models (2,800 ANSI lumens and 2,200 ISO lumens). Actual performance may vary based on usage conditions.
      5 Available games and content may vary by country and model and are subject to change without notice. Certain games require a separate controller. Internet connection and subscription may be required. Requires a Samsung account.
      View the full article
    • By Samsung Newsroom
      “It’s all about making colors truer to the vision of video game creators”
      – Bill Mandel, VP, Samsung Research America
       
      HDR (high dynamic range) technology has been revolutionizing visual quality in movies and TV shows for several years. Now, with Samsung championing HDR10+ GAMING, the same visual transformation is making its way to the video game industry. It’s beneficial for game makers and players alike, and truly makes it possible to get the most visual impact out of gaming’s modern graphics and realism.
       
      Samsung Newsroom sat down with Bill Mandel, Vice President, and Steve Larson, Senior Manager at Digital Media Solutions, Samsung Research America, to discuss HDR10+ GAMING and how the technology is changing the gaming industry.
       
      ▲ Steve Larson (left), Senior Manager and Bill Mandel, VP, Digital Media Solutions, Samsung Research America
       
       
      Gamers and Game Creators Deserve HDR, Too
      While HDR dramatically heightened the visual experience for television and film, its application in video games has been limited. Game engines have built-in color management systems that help the connected TV or monitor know what colors to show. However, a lack of communication between screens and game engines requires users to manually calibrate their displays.
       
      “HDR10+ GAMING establishes a direct line of communication between the screen and the game engine”
      – Steve Larson, Samsung Research America
       
      In search of a solution, SRA started to develop HDR10+ GAMING. By automatically adjusting HDR settings based on the screen’s capabilities, HDR10+ GAMING unlocks a premium visual experience through accurate color, contrast and brightness.
       
      “HDR10+ GAMING establishes a direct line of communication between the screen and the game engine,” said Larson. “The screen can now understand what the game engine is doing, and the game engine knows what the screen can display. That produces a much better visual output.”
       
      “It’s all about making colors truer to the vision of video game creators,” said Mandel.
       
       
      Engineering a Simple Solution for the Artists
      Game developers were the first to call for new technology that addressed the limitations of HDR.
       
      “The initial need came from game developers themselves who want the games they build to look the best they possibly can,” said Mandel. “They were struggling to get colors to look the way they hoped across monitors.”
       
      ▲ Bill Mandel, VP, Digital Media Solutions, Samsung Research America, explains how HDR10+ GAMING was introduced to bring better visual experience to all gamers
       
      “We wanted the specs we published to be simple for game developers to use, without a heavy burden,” said Larson. “Once they integrate our specs into their game engine, they can use it across any game built in that engine. This significantly simplifies adoption across the industry because it doesn’t rely on certain configurations or devices. It’s easy.”
       
       
      Making It Simple for the Players
      With HDR10+ GAMING, gamers no longer need to deal with dials and test patterns to calibrate their monitors.
       
      “HDR10+ GAMING simplifies the process by automatically adjusting settings for games, just like it does for movies,” said Mandel. “This ensures gamers get the best picture quality without any hassle — just turn on the game and go.”
       
      ▲ Bill Mandel (top), VP, and Steve Larson, Senior Manager, Digital Media Solutions, Samsung Research America demonstrate how HDR10+ GAMING automatically elevates the gaming experience
       
      Because HDR10+ GAMING works both on TVs and gaming monitors, gamers can now enjoy a consistent visual experience with immersive graphics across platforms without setting anything up. This standard is especially important as today’s gamers expect photorealistic graphics in gaming today.
       
      “When activated, your device automatically identifies that HDR10+ GAMING is an available option in any compatible game and takes advantage of it,” said Larson. “There’s no need to navigate a hidden menu or adjust settings.”
       
       
      Lowering the Threshold for the Gaming Industry
      For game developers, one major advantage of HDR10+ GAMING is that it is free to implement. With the right application programming interface (APIs), they can integrate HDR10+ GAMING into their existing game engines without any specialized training.
       
      “It’s simple. Once developers integrate our specs into their game engine, they can use it across any game built in that engine”
      – Steve Larson, Samsung Research America
       
      Putting these standards into action, Samsung partnered with NEXON in September 2023 to launch the world’s first HDR10+ GAMING title, “The First Descendant.”
       
      At Summer Game Fest this past June, the company showcased its latest Odyssey OLED gaming monitors with HDR10+ GAMING capabilities. The combination of HDR10+ GAMING and Samsung’s Odyssey OLED gaming monitors demonstrates how advanced display technology can elevate the gaming experience in video games like “Red Dead Redemption 2.”
       
      Moreover, Samsung has worked with partners such as CD PROJEKT RED on “Cyberpunk 2077” — bringing the game’s fictitious Night City, California, to life like never before. The copy was a great hit, selling over 25,000,000 copies worldwide.
       
      “We designed the system to be incredibly simple to implement,” said Larson. “In fact, CD PROJEKT RED told us that they knew HDR10+ GAMING was something they wanted to use. They were impressed with how fast and easy it was to implement. Their team was actually able to get it up and running in about half a day.”
       
      “This is a free license technology. We’ll see a lot more games and platforms adopting the technology”
      – Bill Mandel, VP, Samsung Research America
       
       
      A Radiant Future Ahead for HDR10+ GAMING
      Samsung is looking to expand HDR10+ GAMING to include additional game engines, particularly those that are more niche. The company is already working with major studios and developers to add into their proprietary engines and some of the more widely adopted ones.
       
      “Through collaborations with game companies, we will expand the HDR10+ GAMING ecosystem — ensuring broader adoption and richer gaming experiences,” said Mandel.
       
      This wide network will provide game developers with a versatile and powerful set of tools to create visually stunning games more efficiently.
       
      ▲Steve Larson (left), Senior Manager, and Bill Mandel, VP, Digital Media Solutions, Samsung Research America
       
      “As this is a free license technology, we’ll see a lot more games and platforms adopting the technology,” Mandel continued. “For consumers, it means a consistent and immersive gaming experience across a range of devices — with minimal setup and maximum visual impact.”
       
      Mandel and Larson anticipate a notable increase in the number of developers, games and users leveraging HDR10+ GAMING soon.
       
      “Expect big things to come!” said Mandel.
      View the full article





×
×
  • Create New...