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
      Samsung Electronics today announced that the quantum dot (QD) sheet used in its QD TVs has received certification for compliance with the Restriction of Hazardous Substances (RoHS) directive and has been verified to contain no cadmium by the global certification institute, Société Générale de Surveillance (SGS).
       
      SGS, headquartered in Geneva, Switzerland, is a world-leading testing and certification body that provides services to ensure organizations meet stringent quality and safety standards across various industries, including electronic products, food and the environment.
       
      In addition to receiving recognition from SGS for the no-cadmium technology in Samsung’s quantum dot film, the company’s compliance with the EU’s RoHS directive assures the safety of the TV viewing experience.
       
      “Samsung’s quantum dot TVs are built on safe technology that complies with restrictions on hazardous substances while delivering unmatched picture quality,” said Taeyong Son, Executive Vice President of Visual Display Business at Samsung Electronics. “Achieving SGS certification fully validates the safety of our products. With this recognition, we are committed to continuously developing sustainable display technologies.”
       
      Samsung began researching quantum dot technology in 2001, and its ongoing commitment to research and investment has positioned it at the forefront of innovation in the global display market.
       
      After developing the world’s first no-cadmium quantum dot material in 2014, Samsung launched TVs that implemented the technology the following year. Since then, the company has been leading quantum dot technology through continuous technological advancements.
       
      In particular, Samsung successfully created nanocrystal material without cadmium and has secured around 150 patents for the technology. With this extensive expertise and technological progress, the company has ushered in an era of safer quantum dot TVs made with materials that do not contain harmful substances.
      View the full article
    • 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





×
×
  • Create New...