Loading...
Home
  • Tech Blogs
  • Videos
  • Conferences
    • Droidcon News
    • Upcoming Conferences
    • Become a Partner
    • Past Events
    • Keep Me Informed
    • Diversity Scholarships
  • Community
    • droidcon Team
    • How to Hold a Droidcon
  • Android Careers
Sign In

Global CSS

 

Android Jetpack Compose — Exploring State Based UI

 

 
Rajan Ks
Android Lead at @getloconow. Android Enthusiast, Online gamer.
Published: November 23, 2020
Tweet
Share
 

 

As a developer who is always excited about new enhancements in Technology, I recently started exploring Jetpack Compose, Android’s own Modern UI toolkit to build Native UI in declarative style inspired from Modern frameworks like Flutter, litho etc.

I have been playing with it for a while now and it is super fun, simple and exciting to build user interfaces and state based animations using it, hence thought of spreading the knowledge by sharing what I have learnt using this amazing tool so far.

 

Table of contents

  • Why JetPack Compose
  • Building UI using Compose
  • Handling UI state
  • Interacting with ViewModels
  • Compose LazyGridFor with paging

 

Why Jetpack Compose ?

Like with every new feature, there will always be few mandatory questions which needs to be addressed before the transition, like for starters learning curve of the feature, interoperability with current system and ease of migrating existing code. As per my experience playing with compose for past couple of weeks, it squashes above questions right away

  • Jetpack Compose comes with built-in support for Material Design, Animations, Dark Theme and most of the UI Compose widgets you use in Android.
  • It is interoperable with current Android view system, you can switch to Compose world from view system using ComposeView and from compose to traditional Android views using AndroidView compose function.
  • With interoperability in place, migration is piece of cake and can be done step by step, you can start creating new screens using compose by keeping existing code intact and slowly moving existing screens when and ever you feel comfortable.
  • Declarative, Concise, State based data flow and most exciting part is writing UI in our beloved language Kotlin ❤

Thrilled ? Me too! So without further ado let’s go ahead and build a sample Android Application using Jetpack Compose. Most of the apps includes loading data into lists/grids using a loading and error state, So this article demonstrates most commonly used scenario which is to display a list of items by fetching data from server along with loading and error screens, also paginating them.

 

To start working with Jetpack Compose, Install Android Studio 4.2 latest canary and create new project with Empty Compose Activity template to let IDE set up compose dependencies and Gradle configurations for you. For more information visit https://developer.android.com/jetpack/compose/setup

 

Building UI using Compose

Compose widgets are created using annotating functions with @Composable

We need to first build compose functions for states of screen which are LOADING, ERROR, EMPTY and DATA, also IDLE if needed.

In this case we need three compose widgets to show Loading, Error and Empty UI states. Also let’s make sure error and empty messages are configurable so we can reuse same functions across Application.

 

 

Handling UI State

Now the Compose widgets are ready, time to render widgets based on current state of screen. To do that let’s create enum class with all possible states.

 

 

State is a value holder which holds a value and the compose which is using State to read the value will be subscribed automatically to the changes of value inside that state, meaning when ever the value changes , the current RecomposeScope will be redrawn using new value.

Create a compose function using State value as PageState to draw/redraw compose widgets based on current state of the page

 

 

Interacting with ViewModels

So far so good, State handler Compose widget is ready, but it needs State<PageState> to dynamically update UI, to achieve that let’s create a ViewModel which is responsible to update value of State<PageState> based on current mode and also to fetches data from server alongside providing scope for pagination.

Also to implement paging logic in ViewModel, create a class which appends the new result to existing one

 

 

 

Now to wire compose widgets with ViewModel, Fragment is used as a UI container, and by using ComposeView inside a Fragment, it supports compose widgets

 

 

Perfect! App is almost ready, at this point it can render loading, error and empty UI on Fragment, let’s look at how to create GridView in compose with paging to fill the content part of the screen once loaded.

 

Compose LazyGridFor with paging

Out of the box, Jetpack Compose toolkit provides RecyclerViewequivalentLazyRowFor and LazyColumnFor to stack items vertically and horizontally with lazy implementation. Currently, there is no LazyGridsupport provided in-built.

Create one by merging LazyColumnFor and Row along with few modifications to data. Also make sure proper index of item is calculated as it will be used for paging purposes.

 

 

Create a grid item to populate LazyGridFor and also a model class to bind data into grid item.

 

 

Now Let’s fill Fragment content with data using LazyGridFor and implement paging logic to fetch data page by page.

 

 

🎊 That’s it ! We finished the entire flow of displaying data into grid with loading states in between. Now let’s look at the code in Action! 👏 👏

 

Image for post

 

 

Image for post

 

Image for post

SUCCESS(left), EMPTY(centre) and ERROR (right)

 

The complete implementation of app Plasma is in below repository 👇, It comes with cool Jetpack Compose widgets like Gradient ProgressBar , Button ,Text, State based transitions and much more. Also built using Modern Android Development(M.A.D) tools like flows, coroutines , Navigation, Architecture components, Jetpack Datastore and Dagger Hilt.

 

rajandev17/Plasma

100% Kotlin ❤️❤️ This Benchmark App is built using latest Android tools and Jetpack libraries which includes Jetpack…

github.com

 

Thanks for reading! Please click the 👏 button and share it to help others only if you feel it is worthy!

 

Please drop any suggestions, enhancements, thoughts or queries in comments.

 

Cheers! and Happy Coding ✌️

 

 

 

Tags: Android, Kotlin Coroutines, AndroidDev, Android App Development, Jetpack Compose

 

View original article at: 


 

Originally published: November 06, 2020

Android News
Compose CameraX on Android
Compose CameraX on Android

By Peng Jiang

Android new UI toolkit Jetpack compose is in beta now, which has all the features you need to build production-ready apps. CameraX is another Jetpack support library, which let you control the camera easier. As compose is still under development, lots of the views are still not available the compose way.

By ProAndroidDev -
Android News
Getting… your BottomSheetScaffold working on Jetpack Compose Beta 03
Getting… your BottomSheetScaffold working on Jetpack Compose Beta 03

By Carlos Mota

It’s Monday, no releases this week, and… there’s a new version of Jetpack Compose — beta 03—available. What a perfect time to just increment 02 to 03 and see what’s new. The API is (almost) final so after updating from alpha to beta there weren’t any big changes to do. However, and remember that’s still in development, there’s always something that I need to update. 

By ProAndroidDev -
Android News
Noisy Code With Kotlin Scopes
Noisy Code With Kotlin Scopes

By Chetan Gupta

Scopes make your code more readable? think again... You are going to encounter these scope functions namely let, run, apply, also, within every Kotlin codebase, along with all the mischievous ways developers exploit their usage from the way they were intended for. Let see how popular opinion on those ends up just as a code noise.

By ProAndroidDev -
Android News
Improving Android DataBinding with Bindables library
Improving Android DataBinding with Bindables library

By Jaewoong Eum

DataBinding is one of the most important factors for MVVM architecture. The basic concept of DataBinding is to link the view and view model via observer patterns, properties, event callbacks, etc. Linking and automating communication between the view via the bound properties or something in the view model has a lot of benefits in the MVVM architecture concept.

By ProAndroidDev -
droidcon News

Tech Showcases,

Developer Resources &

Partners

/portal/rest/jcr/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/home-details/EmployerBrandingHeader
EmployerBrandingHeader
https://jobs.droidcon.com/
/portal/rest/jcr/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/jobs-droidcon/jobs.droidcon.com
jobs.droidcon.com

Latest Android Jobs

http://www.kotlinweekly.net/
/portal/rest/jcr/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/kotlin-weekly/Kotlin Weekly
Kotlin Weekly

Your weekly dose of Kotlin

https://proandroiddev.com/
/portal/rest/jcr/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/pad/ProAndroidDev
ProAndroidDev

Android Tech Blogs, Case Studies and Step-by-Step Coding

/detail?content-id=/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/Zalando/Zalando
/portal/rest/jcr/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/Zalando/Zalando
Zalando

Meet one of Berlin's top employers

/detail?content-id=/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/Academy for App Success/Academy for App Success
/portal/rest/jcr/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/Academy for App Success/Academy for App Success
Academy for App Success

Google Play resources tailored for the global droidcon community

Follow us

Team droidcon

Get in touch with us

Write us an Email

 

 

Quicklinks

> Code of Conduct

> Terms and Conditions

> How to hold a conference

> FAQs

> Imprint

Droidcon is a registered trademark of Mobile Seasons GmbH Copyright © 2020. All rights reserved.

powered by Breakpoint One