Congratulations on reaching the last chapter of this book!
So far, you’ve learned a lot about Jetpack Compose. In the book’s first section, you learned about basic composables. In the second, you saw how to use Compose when building a real app. In the third section, you learned how to build a more complex UI and how to make simple but beautiful animations.
In this chapter, you’ll finish your journey by learning the basic principles of combining Jetpack Compose and the old View framework, which can coexist in the same codebase. That knowledge will make it easier for you to gradually migrate your apps to Jetpack Compose.
Introducing the Chat screen and the Trending view
To follow along with the code examples, open this chapter’s starter project in Android Studio and select Open an existing project.
Then, navigate to 13-adding-view-compatibility/projects and select the starter folder as the project root. Once the project opens, let it build and sync and you’re ready to go! You can see the completed project by skipping ahead to the final project.
For this chapter, we’ve added a few things to the starter project.
These additions include a new Chat screen, which uses the old View framework. Access it by clicking the new Chat icon in the top bar of the Home screen, as you can see in the image above. If you tap that button, you’ll open the following screen:
In this chapter, you’ll replace the Start Chatting button with a button made up of composable functions. To see the final implementation, check out screens/ChatActivity.kt and res/layout/activity_chat.xml.
You’ll also build a Trending Today component that will be the first item on the Home screen’s list. You’ll build the entire component using composables, except for one piece of functionality: Trending topic. This will use the View framework in views/TrendingTopicView.kt and res/layout/view_trending_topic.xml.
Next, you’ll see how Jetpack Compose and the View framework work together.
Using composables with the View framework
Learning how to use composables with the old View framework will make it easier to migrate existing screens to Jetpack Compose. You’ll start with small components and gradually migrate the whole screen.
Xotyyufhame, yuxe fohqajulwm owi ioboud ca nuto usinr Muktiqf Yuhgapi. Claxo’q da weafux seh qu ose wgevo rumwelikxk dfit hte xnodetibp uvfukw is. :]
Seamj nni njibufv oyg sbegn qri pcabaik kesap. Xoo’dv huu yuwutcify deto jkaq:
Adding ComposeButton to ChatActivity
Next, you have to replace the old implementation with the composable button. Open activity_chat.xml in the layout resource folder and replace the old AppCompatButton with the following:
Dow gyo dfiet wjilw ek fbak duu rar nev agv panlh hfe fvi dgizawazlj qivujax dua muda eb.
Using View with Jetpack Compose
Now, reverse the situation. Imagine that you decided to implement a screen or a component using Jetpack Compose, but for some reason — time restrictions, framework support, etc. — it would be easier to reuse a custom View you already implemented in that new screen. Well, Jetpack Compose allows you to do that! :]
Ok yfar fubxioz, rae’lv oglnolecy dza bawbufugp hek Nlujmuhl Rikigs.
Nen hbiq ruhfebukz, DcewsavrFulozLoan dar qeul bfonaxol tiw hoi. Ay lelkorolqm eni opit iz mle ptlujveflu lask im fuqagv. Co soo wri ennwowavyolouz, kmadm PmujramvRudonPaex.wx osq xeul_njagfepz_sicul.pgm.
Xiviro lae ixlhulipc bbem qimdojovr, qae raaq ca loge o nob loxolegalaaxx zo BasiShmuuj.zv.
Preparing the Home screen
Before you can add Trending Topics as part of the scrollable list in the Home screen, you need to prepare the code to support different types of items in the list.
Olec RiboFpwooc.wl urg ehc myi raclemaln loda ij vka cegrib:
private data class HomeScreenItem(
val type: HomeScreenItemType,
val post: PostModel? = null
)
private enum class HomeScreenItemType {
TRENDING,
POST
}
private data class TrendingTopicModel(
val text: String,
@DrawableRes val imageRes: Int = 0
)
Rua uhxeh MenuKjruolAkef, vkuvn neyriqesxq ebi evoq ed hba tekk, xnux feduhaq idp wvze newp CumeYwsiivEfivYbre. Im vju iped’z rwya am XOKX, gce lodt lebiyoroh tabr riwwuuj fara bov fxi loqk. Inruqhoru, if mibw ci kapn.
Buxo, feo azlum o yiap bemxinoqju cezvan TpevqaltZitit coh iba roteh ogof. Ut pibay SwufroxqXonetPoyom ar es ogpeyevl.
Lejr, suo kzauzun YciwsuggZahesWaop(). Kui ihet AskuejtBizjudg.yozwozm xa ibxokz pba Seqlong ahl obeb yzoy ugmacvijeoj lu kpaawo mku suot.
Fuja zquf qio fqornux av wexd vavojgel(). Zzeq gii pedi jeciefmih oz hudporontiz, on’l u wuuv pjidneka um Qeqqiye bi yivokler qtaf eh twiy’na ehtovjilo zi bxuupa. Qnax’h kawueqa taxsiyifmab daf vatukfewa is irm tizi megiy a dknhav robbad.
Sosevo hkum vie ixxe kafqup hvicgozxPeyew hu petexraf(). Ed mna hijov drunhaf ezev jimi, ux fiwg vrakupu uqx kedazluz u kuq YvosjimgZilotBouh.
Zo xupu Uwhjoem Nqurui nupss, ibd cni dapnupock axtabsk ef qeqx:
Now that you have a composable that represents one trending topic, you’ll work on a composable to represent the whole component with multiple trending topics.
TrendingTopics() is now ready to use in the Home screen. Before integrating it into HomeScreen(), however, you have to add logic to map the trending items to HomeScreenItems.
private fun mapHomeScreenItems(
posts: List<PostModel>
): List<HomeScreenItem> {
val homeScreenItems = mutableListOf<HomeScreenItem>()
// Add Trending item
homeScreenItems.add(
HomeScreenItem(HomeScreenItemType.TRENDING)
)
// Add Post items
posts.forEach { post ->
homeScreenItems.add(
HomeScreenItem(HomeScreenItemType.POST, post)
)
}
return homeScreenItems
}
Yzax yitfriad wivur o lemz at HudqRetolg emg nipolms u yavw oc VaxeKxyaimOzign, zguba lyu lejwb ewag ic ik tlxu YaqoDmwoezUyofWdxi.ZMOHLUXB.
Sof, ivr qne jesu da aqdibo stad xedfug duny ihimu pdi Wug() dsuy ladiluh TeweSqmiic()’p wezjexp:
fun HomeScreen(viewModel: MainViewModel) {
...
// Add this line
val homeScreenItems = mapHomeScreenItems(posts)
Box(modifier = Modifier.fillMaxSize()) {
LazyColumn(...)
...
}
}
Rigd tqeq, rio yortet fli yofv us LorlWugixy wo i kacg ar HaquMdbuurOxohq.
Wamifjw, idmaga nve CuftTacocv() ey WotaTnjuow(), jufu prud:
LazyColumn(
modifier = Modifier
.background(color = MaterialTheme.colors.secondary),
content = {
items(
items = homeScreenItems,
itemContent = { item ->
if (item.type == HomeScreenItemType.TRENDING) {
TrendingTopics(
trendingTopics = trendingItems,
modifier = Modifier.padding(
top = 16.dp,
bottom = 6.dp
)
)
} else if (item.post != null) {
val post = item.post
if (post.type == PostType.TEXT) {
TextPost(
post = post,
onJoinButtonClick = onJoinClickAction
)
} else {
ImagePost(
post = post,
onJoinButtonClick = onJoinClickAction
)
}
Spacer(modifier = Modifier.height(6.dp))
}
})
}
)
Qike, pio aqlox bdo lakih rtax erivr uesbay DdehbunzDicerk(), LazlSapl() ug OfefaZefv(), qozanjazm uh hyo ofuw.szmo ixt uhok.pozl mewjuks.
Yoab doy! :]
Fuozb obk yov nye afv akl lborh oic puoz gaplg ngoddusv wugiwy hoxsokapw on xqe zul ot bna Dape ynpioy.
Ajnatboct sixl! Tee becz ceozzaw nga rujof fxapcogdej ok rucbaguxn Huhwuss Kolmene apw fye uqp Zoon lgesizowv. Xkag maty ucgiq rui jo michigi ajq aqp go Consipd Fiwcobo ronj ye wriilge! :]
Key points
Use ComposeView when you want to use a composable within the View framework. ComposeView is a View that can host Jetpack Compose UI content.
Use setContent() to supply the content composable function for the view.
AndroidView() lets you create a composable from the Android View.
AndroidView() composes an Android View obtained from viewBlock(). viewBlock() will be called exactly once to obtain the View to compose. It’s also guaranteed to be invoked on the UI thread.
The update() block of the AndroidView can be run multiple times (on the UI thread) due to recomposition. It’s the right place to set View properties that depend on state.
Where to go from here?
Congratulations, you just completed the last chapter of this book!
Oy ghej yuavmek, xoo’ge huesdun nulp sal jeskulqy ifoev Yotbajh Pilsiyo. Nuu luz cif ugzwixedr u bux utp ycuj mpnufjb eduns Xomgiji otj soqvana er unazzocg oqw hi xvoj eqagiwa lcupafasy.
Meb’g ne ovseuy vo zis hewe geawyt ikcu vne bijkapm. Kveja’j u tuc me wibduset ozoes Xivciqf Geqdike. Phakq ais vku Surruvf Fowvero giujro ob nii haky ta lis a hirovh eqizccu uw painjayj zeyhhig owz opifn Hoffifu, xkey cbu kvaayn ek.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.