Jetpack Compose: Custom List? Such ez, much wow.
Populating a list with a custom format is quite tiring when we do it the usual way in Android.
Note: This is just a quick comparison and discussion on how Jetpack Compose made our lives easier.
For example, we need to create a custom list like this in a usual way.
PS: The actual app is not laggy. I just converted the video to gif and reduce frames and size.
Step 1: We need to create an XML file for the card design
Step 2: Add the Recycler View to the main XML file:
Step 3: Create an Adapter
Step 4: Create a View Holder
Step 5: Populate your list in your MainActivity
Phew… ( ˘︹˘ ) katamad…
So what Jetpack Compose offers? If your layout is as simple as in the gif above, all you need is one Kotlin file for creating a view and populating a list of characters. No more adapters, view holders, and XMLs.
MainActivity.xml we need to create these methods:
fun MainScreen() — this method will serve as a canvas for our items
- This method is different from your usual method.
- The naming convention for Composable method should start in a capital letter
@Composableannotation means that the method below is a Composable
@ExperimentalFoundationAPIannotation means that we used a certain pre-defined composable method that is still experimental inside our created method. In our case, it’s
fun CharacterCard() — for creating the card
fun CharacterImage() — for creating the image view/layout
fun CharacterContent() — for creating text views (character name and status)
Method 5 (Optional):
fun AppBar() — for creating an appbar/toolbar
Then on our onCreate method we have:
What's good with Jetpack Compose?
Here are some:
- All the methods we have created are dynamic and reusable. Remember that we create our Composable method outside our class, meaning it was declared globally and publicly by default so it can be reused anywhere you want.
- We eliminate the creation of XML files. For some beginners, XML is somehow confusing, and you have to learn it separately. In Jetpack Compose, we only need one language, that is Kotlin.
- Compose used a declarative approach, compose function has a state, whenever the state changes, the whole compose layout rebuilt.
- Compose can be nested easily. Meaning a compose child can have many parents and children can inherit/nest from one another.
- If you are knowledgeable with Flutter, you might find it easier because of its structure.
Since I am using the version 1.0.0-alpha10 in this example and Android Studio Canary for IDE, debugging is a little bit hard because the preview loads too long. But it’s understandable because it’s under development.
But I am excited to implement this for my future projects!
Check out these awesome projects that used Jetpack Compose! https://github.com/android/compose-samples
I’m still learning, please leave a comment if there’s something I need to improve/learn/elaborate. Thank you!