Quantcast
Jump to content


Recommended Posts

Posted

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



  • 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
      January 2025 Unveiling Invites to "Galaxy Unpacked 2025" Ushering in a New Era of Mobile AI
      New Galaxy products are unveiled at Galaxy Unpacked 2025! Galaxy Unpacked 2025 commences on January 23, 3 AM KST (January 22, 10 AM local time) in San Jose, USA. It is streamed live online via the Samsung Electronics Newsroom, Samsung.com, and Samsung Electronics YouTube channel. Samsung Electronics' innovations are going to usher in a new era of the mobile AI experience with the natural and intuitive Galaxy UI. See for yourself.
        Learn More Highlights from the CES 2025 Samsung Press Conference
      On January 6, Samsung Electronics held the CES 2025 Samsung Press Conference under the theme "AI for All: Everyday, Everywhere," unveiling its technological visions. The full inter-device connectivity and hyper-personalized user experience through AI, both introduced at the conference, have attracted media attention from all over the world. Check out the innovative technologies that will change the future in our video.
        Learn More Updates for Samsung In-App Purchase: Resubscription and Grace Period Features
      Managing subscriptions is now more convenient with the new Samsung in-app purchase (IAP) updates. The newly updated features are resubscription and grace period.
      Users can now reactivate their canceled subscription in Galaxy Store using the resubscribe feature. Even if there is a problem with the payment when renewing a subscription, the subscription is not canceled if the problem is resolved during the set grace period. If the developer activates the grace period feature in the item settings of Galaxy Store's Seller Portal, the system automatically retries the payment and sends the information about the failed automatic payment to the user so that they can change their payment method.
      Developers can also see new information in the subscription API and ISN services, such as the subscription API's response parameters and ISN service events. Manage your subscriptions more effectively using these new features. Tutorial: Manage the Purchase/Subscription of Digital Items with Samsung In-App Purchases
      The hassle of managing digital item purchases and subscriptions is no more! Samsung in-app purchase (IAP) is a powerful tool that provides a more secure and convenient payment environment for users and expands commercialization opportunities for developers. This tutorial covers how to smoothly and efficiently implement item purchase/consumption processing and subscription management. A step-by-step guide and practical code examples are used to walk developers through the complex API integration process even if they're just starting out. Check out the tutorial on the Samsung Developer Portal.
        Learn More Tutorial: Step into Galaxy Watch Application Development Using Flutter
      Did you know that you can develop an application for Galaxy Watches with a single codebase? The tutorial shows software developers how they can develop applications for Galaxy Watch using the Flutter framework. Flutter is an open-source framework for building multi-platform applications from a single codebase. An easy step-by-step guide that can be followed without much preparation is provided for beginners, as well as practical tips and a code example for Flutter developers who are new to developing Galaxy Watch applications. Check out the tutorial and start developing Galaxy Watch applications!

      Learn More Tutorial: Monitoring Your Cards in Samsung Wallet in Real Time
      Do you want to monitor the status of cards added to Samsung Wallet on user devices in real time? Samsung Wallet provides the Send Card State API to make it easy to track the cards, as the API notifies the server of any changes whenever a card is added, deleted, or updated.
      The tutorial covers how to set up server notifications, how to receive notifications to a Spring server, and how to securely verify the received notifications. Learn how to monitor the status of cards in Samsung Wallet in real time.

      Learn More Samsung Electronics Demonstrates AI-RAN Technologies, Paving the Way for the Convergence of Telecommunications and AI
      Telecommunications technology is evolving beyond just improvements in data transmission speed, moving towards emphasizing user experience, energy efficiency, and sustainability. Samsung Electronics is accelerating the emergence of the era of future communications by showcasing the AI-RAN technology which integrates AI technology with the Radio Access Network (RAN), which is the core technology for communications networking.
      In particular, at the Silicon Valley Future Wireless Summit held in November 2024, Samsung Electronics demonstrated the results of the AI-RAN PoC to global communications providers, the first in the industry to do so. The technology indicated a possibility to greatly improve data throughput, communication coverage, and energy efficiency compared to the existing 5G RAN. It also proved the convergence of communications and AI could significantly enhance network performance. Learn more about Samsung Electronics' AI-RAN technology that goes beyond the boundary of communications and creates smarter networks with AI.

      Learn More Building a Trusted Execution Environment on RISC-V Microcontrollers
      In embedded systems such as IoT devices, it is crucial to protect sensitive data. For this, a Trusted Execution Environment (TEE) is required. It creates an isolated environment within the processor, so that security-sensitive tasks can be executed without risk of external threats.
      Samsung Research is conducting a study on how to implement the TEE technology on RISC-V-based microcontrollers (MCU), an open-source hardware architecture, and has introduced mTower, a core project related to this study. Learn more about stronger security for IoT devices on the Samsung Research blog.

      Learn More   
      https://developer.samsung.com

      Copyright© %%xtyear%% SAMSUNG All Rights Reserved.
      This email was sent to %%emailaddr%% by Samsung Electronics Co.,Ltd.
      You are receiving this email because you have subscribed to the Samsung Developer Newsletter through the website.
      Samsung Electronics · 129 Samsung-ro · Yeongtong-gu · Suwon-si, Gyeonggi-do 16677 · South Korea

      Privacy Policy       Unsubscribe

      View the full blog at its source
    • By Samsung Newsroom
      Samsung Electronics today announced the integration of Eclipsa Audio — a groundbreaking 3D audio technology developed in partnership with Google — into its 2025 TV and soundbar lineup. By empowering creators to craft dynamic, immersive audio content and enabling seamless playback on Samsung TVs, Eclipsa Audio brings captivating audio and visual experiences closer to consumers than ever before.
       
      “We are proud to lead the industry with the integration of Eclipsa Audio into our 2025 TV and soundbar lineup,” said Taeyong Son, Executive Vice President and Head of the R&D Team, Visual Display Business, Samsung Electronics. “This innovation opens new possibilities for immersive audio experiences and reinforces our commitment to shaping the future of home entertainment.”
       
       
      Innovating the Home Entertainment Experience
      Samsung, the global leader in the TV market for 18 consecutive years, is redefining home entertainment with the integration of Eclipsa Audio. With the largest market share over 75 inches worldwide, Samsung TVs are poised to make this groundbreaking technology accessible to more consumers than ever before.
       
      Eclipsa Audio allows creators to adjust audio data such as the location and intensity of sounds, along with spatial reflections, to create an immersive three-dimensional sound experience.
       
      As the first in the industry to adopt Eclipsa Audio, Samsung is integrating the technology across its 2025 TV lineup — from the Crystal UHD series to the premium flagship Neo QLED 8K models — to ensure that consumers who want to experience this advanced technology can choose from a wide range of options.
       
       
      Expanding Content and Playback
      Starting in 2025, creators will be able to upload videos with Eclipsa Audio tracks to YouTube. Viewers with 2025 Samsung devices will be able to watch YouTube videos with premium spatial audio when available.
       
      To ensure consistent audio quality, Samsung and Google are working with the Telecommunications Technology Association (TTA) to create a certification program for devices using Eclipsa Audio, ensuring that consumers experience the highest standards of sound fidelity.
       
      “We believe that Eclipsa Audio has the potential to change the way we experience sound,” said Jim Bankoski, Vice President of Engineering, Google Chrome. “We are excited to see how the creator community uses it to create new and innovative audio experiences.”
      View the full article
    • By maljaros
      There is no native Strava mobile app for Tizen OS smartphones, so what app could be used for tracking trail run and cycling activities on a Samsung Z4? Or is there a "non-native" route to Strava itself?
      Thank you, Maljaros
    • By Samsung Newsroom
      Samsung Electronics added a new dimension to cinematic storytelling with The Wall Micro LED display at this year’s world famous Venice Biennale Art Festival.
       
      At the festival, The Wall Micro LED is showcasing director Marco Perego’s latest film Dovecote, starring Zoë Saldaña. Dovecote is a poignant film about a woman’s emotional journey as she leaves the prison and the deep bonds she formed with fellow inmates.
       
      The screenings, scheduled until the close of the festival on November 24, take place in a unique setting at the Vatican’s official pavilion located in the Giudecca women’s prison. This venue adds layers of emotional depth to the film as it is also where the piece was filmed, heightening the themes of freedom, belonging and resilience.
       
      ▲ The Giudecca Women’s Prison, the filming location and venue for the screening of Dovecote
       
       
      Unparalleled Visual Artistry With The Wall
      Renowned for its celebration of artistic expression, the Venice Biennale became a stage for technological innovation with Samsung Electronics’ involvement this year. Perego’s Dovecote demanded a display capable of capturing its emotional intricacies, including the strong bonds formed between the inmates and the isolation they endure. The superior color accuracy and contrast of The Wall made it the ideal choice.
       
       
      The collaboration between Perego and Samsung was a natural fit. Samsung Electronics provided advanced display technology and technical support from installation to execution, ensuring the visual depth intended by the director.
       
       
      Groundbreaking Micro LED Technology Elevates Visual Art to New Heights
      Samsung Electronics’ cutting-edge Micro LED technology was selected to showcase Perego’s Dovecote. The Wall’s 1.2mm pixel pitch IWA model was chosen for its ability to immerse viewers in the film’s delicate visual nuances.
       
      ▲ Film director Marco Perego viewing a screening of Dovecote
       
      With Samsung’s The Wall, Perego was able to realize his artistic vision, presenting his film with the superior display needed to convey the precise hues and contrasts achieved during the color grading process. The immersive experience enabled by Samsung’s display technology was key to the film’s success in captivating artists, curators and art enthusiasts worldwide.
       
      “The most important thing after you finish a film is how you show this film,” said Perego, following the premiere on August 17. “Thanks to the collaboration with Samsung, we were capable of really bringing out the right color and the right contrast to achieve the emotional impact I envisioned for the film.”
       
      The Wall’s Micro LED technology delivers deep blacks and amazing contrast, intensifying the emotional weight of each scene while fully immersing viewers in the film’s themes and the performances of Saldaña and the cast.
       
      ▲ Samsung Electronics team alongside director Marco Perego and actor Zoë Saldaña
       
      This collaboration stemmed from Samsung’s long-standing relationships with Hollywood industry professionals, including previous work with the Cinema LED Onyx. Originally shot at 23.98 frames per second in cinema color spaces, the teams worked together to seamlessly integrate Dovecote‘s cinematic elements with The Wall’s advanced display technology, pushing the boundaries of traditional screens.
       
      “The Wall’s Micro LED technology resulted in a collaboration that delivered a screening with all of the elements great for the art industry,” said Paul Maloney, Head of Hardware Tech Consulting, Europe Display Office, Samsung Electronics. “For Samsung, it has been an honor to have supported Marco Perego’s film and achieve the artistic vision he had imagined.”
       
      ▲ Director Marco Perego with Paul Maloney, Head of Hardware Tech Consulting, Europe Display Office, Samsung Electronics during the Dovecote screening
       
      “We are incredibly proud to contribute to this unique project,” said Ben Holmes, Director of Display Marketing, Europe Display Office, Samsung Electronics. “The Wall’s superior picture quality, coupled with its ability to bring out the minute details and vibrant colors, perfectly aligned with Marco Perego’s vision of creating an immersive experience to draw viewers into the themes of the film.”
       
       
      Empowering Creators with Cutting-Edge Display Technology
      Samsung continues to push the boundaries of display technology with The Wall, empowering creators in film and art. The Wall for Virtual Production (IVC model) is another prime example that enables companies and producers to innovate their productions. The ultra-large LED walls are created for virtual content, which seamlessly integrates real-time visual effects to reduce production time and costs.
       
      Samsung’s The Wall displays have been utilized by artists worldwide to bring their creative visions to life. For example, contemporary Korean art leader, the late Park Seo-Bo, showcased his masterpiece on The Wall All-in-One (IAB model) 146-inch 4K screen at New York’s Rockefeller Center.
       
      ▲ Park Seo-Bo’s “Écriture” series, digitally rendered on The Wall’s 146-inch 4K screen, at the “Origin, Emergence, Return” exhibition, Rockefeller Center, New York.
       
      Likewise, Dutch-American audiovisual artist 0010×0010 used The Wall All-in-One during an exhibition in Bangkok, Thailand, to explore the convergence of digital and physical worlds. These are just a few examples of how The Wall is helping to redefine the boundaries of modern art.
       
      Samsung Electronics’ participation at the 60th Venice Biennale is more than just a milestone in its support of the arts; it is a testament to the future of art and technology converging. By continuing to push the limits of display technology, Samsung opens new possibilities for creators across the globe, allowing them to tell their stories with unparalleled visual depth and clarity.
      View the full article





×
×
  • Create New...