Jetpack Compose

Jetpack Compose

Jetpack Compose is a modern UI toolkit that is designed to simplify UI development in Android. It consists of a reactive programming model with conciseness and ease of Kotlin programming language. It is fully declarative so that you can describe your UI by calling some series of functions that will transform your data into a UI hierarchy. When the data changes or is updated then the framework automatically recalls these functions and updates the view for you. In this article, we will see some of the basic topics which are helpful before starting with Jetpack Compose.

  • What is Jetpack Compose?
  • What are its benefits?
  • What challenges we can solve by using Jetpack Compose?
  • Some basic functions of Jetpack compose.

What is Jetpack Compose??

Jetpack Compose is a modern UI toolkit recently launched by Google which is used for building native Android UI. It simplifies and accelerates the UI development with less code, Kotlin APIs, and powerful tools.?

Jetpack Compose is totally declarative programming, which means you can describe your user interface by invoking a set of composable.For past ten years we have been using a traditional way of imperative UI design.

Imperative programming vs Declarative programming

Imperative UI This is the most common paradigm. It involves having a separate prototype/model of the application’s UI. This design focuses on the how rather than the what. A good example is XML layouts in Android. We design the widgets and components which are then rendered for the user to see and interact with.

Imperative UI sample code:

XML:
   <TextView
        android:id="@+id/tv_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
     />        
Kotlin:
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_checkbox)

        tvName.text = "Hello World"
    }
}        


Declarative UI

This emerging design trend emphasizes designing the user interface based on received data, focusing on "what" needs to be displayed. It promotes using a single programming language to create the entire application.

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            Text(text = "Hello World")
        }
    }
}        
In JetPack Compose there is no need for any xml code. We can create views using composable.

Composable Function

It's same as any function in programming. But we need to annotate with @Composable annotation.

Syntax:

@Composable
fun MethodName(parameter: String) {
    //your content 
}

        

Example:

@Composable
fun Greeting(name: String) {
    Text(text = "Hello $name!")
}        

In this example we created new composable function - Greeting(). We use the Text() as content. It's an inbuilt composable function. We can add composable functions to another composable function.

After creating a composable function we can use it as content.

Sample Hello world App using Jetpack Compose:

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            Greeting("World")
        }
    }
}
@Composable
fun Greeting(name: String) {
    Text(text = "Hello $name!")
}        

What are the Benefits of Using Jetpack Compose??

  • Declarative: It is fully declarative so that you can describe your UI components by calling some predefined functions.
  • Compatible: It is easily compatible with the existing views present in Android.
  • Increase development speed: Previously developers have to work on the XML file and Kotlin file. But with the help of jetpack compose this becomes easy and developers only have to work on the Kotlin files.
  • Concise and Idiomatic Kotlin: Jetpack Compose built the UI with the benefit that Kotlin brings.
  • Easy to maintain: As the codebase of any application is present in a single file. It becomes easy to manage and handle the codebase of the application.
  • Written in Kotlin: The application written using jetpack compose uses 100 % of Kotlin programming language.

What Challenges Do We Can Solve using Jetpack Compose??

  • When writing our code we create multiple methods for different purposes. After that we couple this method in our main function according to our requirement. In Android when building any type of view and setting data to that particular view. First of all, we initialize that view with a variable and then add data to that specific view. This process of coupling UI elements with the View Model is called Coupling. When our code is having so many couplings it becomes difficult to maintain this code. So coupling can give you sometimes some Null Reference errors.
  • While developing apps in kotlin we generally prefer using View Modal concept in which we find each view from our XML layout file inside our class and add data to that specific view according to our requirement. In most apps, we use the UI elements to display dynamically so this may sometimes give you an error of NullReference. In this method, UI elements are declared in XML language whereas the functionality is written in java or Kotlin and we link UI elements with our Java or Kotlin class with the findViewbyId() method.
  • If we will prefer to use the same language for writing our UI components and for adding the functionality it will become easier to maintain our code. By using this method the number of couplings inside our code will also reduce.


Some Basic Functions of Jetpack Compose

  1. Composable Function: Composable Function is represented in code by using @Composable annotation to the function name. This function will let you define your app’s UI programmatically by describing its shape and data dependencies rather than focusing on the UI construction process.
  2. Preview Function: The name of the function itself tells us that the function is used to generate the preview of the composable function. It is used to display a preview of our composable functions within our IDE rather than installing our APK in an emulator or a virtual device. The preview function is annotated by @Preview.
  3. Column & Row Function: The column function is used to stack UI elements in a vertical manner and row function is used to stack UI elements in a horizontal manner. Column will stack all the children directly one after another in a vertical manner with no spacing between them and It is annotated with Column(). Where as row function will stack all the children one after the other in a horizontal manner with no spacing between them. It is annotated with Row().
  4. Box: A widget that is used to positioned elements one over another. It will position its children relative to its edges. The stack is used to draw the children which will overlap in the order that they are specified. It is annotated with Box().
  5. Spacer: It is used to give spacing between two views. We can specify the height and width of the box. It is an empty box that is used to give spacing between the views. It is annotated with Spacer().
  6. Vertical Scroll: If the UI components inside the app do not fit the height of the screen then we have to use the scrolling type of view. With the help of a vertical scroller, we can provide a vertically scrolling behavior to our view. The contents inside the vertical scroller will be clipped to the bounds of the vertical scroller. It is annotated with VerticalScroll().
  7. Padding: The padding function is used to provide extra white space according to the requirement around the specific view. It is simply annotated with Padding().
  8. Lazy List: This composable is equivalent to a recycler view in android’s view system. It is annotated with LazyColumn().


Should I use Jetpack compose in my existing Android Studio?

If you are using stable version - Answer is No.

You need Android studio Beta Version. Beta version link .

And also you need to add some dependencies for Jetpack Compose.

//compose_version = '1.0.2'
implementation 'androidx.activity:activity-compose:1.3.0-alpha06'
implementation "androidx.compose.ui:ui:$compose_version"
implementation "androidx.compose.material:material:$compose_version"
implementation "androidx.compose.ui:ui-tooling:$compose_version"        

Final thoughts

Compose provides a modern approach to defining your UI that enables you to separate concerns effectively. Because Composable functions are so similar to normal kotlin functions, the tools with which you write and refactor them will fit neatly into your kit of Android development skills.

In the next post, I’m going to shift the focus to some of the implementation details of Compose and its compiler. For additional resources on Compose, discover more here.

Shubham Jain

Sr. Android Developer | Passionate About Scalable & User-Centric Apps

12 个月

Hello Good morning, I am stuck in an issue Could you please help me out

回复

要查看或添加评论,请登录

Shubham Sharma的更多文章

社区洞察

其他会员也浏览了