Jetpack Compose: Introduction

Jetpack compose is a group of Android libraries that follow the best standards included in Jetpack. It is Google's brand-new, cutting-edge declarative UI framework for creating Android apps.

The primary distinction between Jetpack Compose and XML is that the former is written completely in Kotlin. Layout, style, typography, color, and other UI-related aspects can now be implemented without using XML.

@Composablefun 
fun getText() 
{    
	Text("Hello World!")
}

For developers who use declarative programming, Jetpack Compose offers a straightforward and recognizable experience to patterns that are almost identical to those of other declarative frameworks like Flutter.

Code Comparison with Example

In declarative UI,  we don't need to use the views, textViews, buttons, LinearLayout, etc., that you are familiar with. We can use composable functions instead of setting the layout in the activity files that we used to do with XML.  

Functions annotated @Composable represent an individual UI element in Jetpack Compose. We can also use pre-defined Composables or define our own.

@Composable
fun getCol(){
   Column() {
       Text(text = "Hello")
       Text(text = "World")
   }
}

In XML  

<LinearLayout 
  android:orientation="vertical"
  android:layout_width="match_parent" 
  android:layout_height="match_parent">
  
    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content"
     android:text="Hello"/>

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="World"/>
     
</LinearLayout>

In the examples above, it is evident that the code needed to build the same UI in Jetpack Compose is more readable and requires significantly less number of lines of code compared to its XML counterpart.

Why should I use Jetpack Compose?

  • Code is more readable, clearer, and superior to the previous method of building UI in XML.
  • Less code as compared to XML.
  • Improves build times and APK size.
  • Composable functions can hold a state and re-run on state changes.

Conclusion

With the adoption of declarative UI offered by Jetpack Compose, we can achieve quicker and more efficient development cycles and better performance in our Android applications. You can read more about it here.



Daksh
Hey, I Am Daksh Bhardwaj, A Tech Enthusiast , My Core Interests Lies In Hybrid App Development And Web Development Using Latest Tools And Techniques. Improving every day!