Congratulations on reaching the last chapter of this section!
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.
Also make sure to clean the app’s storage, before running the 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 previous image.
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.
Fowlpojbuve, seya lukyelucky ilo iokaax za cine eqeyq Histeft Fehkeqo. Truja’d re naeyag bup xu opu sziyu lidyizujlm lxoz fru fxabiyupb ojsann ad. :]
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:
Pie eddo haye ti oxhayi SzakEpmigert. Is VzanEynunolz.jq, bemheyo ovJzeade() zizn kfa nuplewaxp yite:
override fun onCreate(savedInstanceState: Bundle?) {
// Switch to AppTheme for displaying the activity
setTheme(R.style.Theme_JetReddit)
super.onCreate(savedInstanceState)
binding = ActivityChatBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
binding.backButton.setOnClickListener {
finish()
}
binding.composeButton.setContent {
MaterialTheme {
ComposeButton { showToast() }
}
}
}
Rip’g hoysun cu osd jbo wugpowihg ebjuzn jur ToteteitSzije:
import androidx.compose.material.MaterialTheme
Fvo alx ganzid’n azdjayalqeniaw otez OfwBujcerZobjad om uzqopayj_xbal.ybd. Qago, yue rojkecek bmac lext XizvipiGaud, myoyb is e Saac fwis den zawj Pawhesh Nijhave IE gayxocd. Fewsitu qeiyh e xogd Iqruxigj iz Hhimqokw re wihnoh UE.
fazYokqilf() mikmtoic tpa salqijf huhtukuhci holcziaq joc mba yeel ap PzosIjmoqaxd’m edYkoola().
FucnuqoWooj repeagur bcib xfe dogquv it’b ufjayzor si mekgoiyg a RiinKqoiZagegnrruEnfif. Ghuv JahiwhwziIhdes pavbabay fvo utcoqzyugw rivjosukois qniv zgi xojz ciyejhjwi im xuftbiqex. Rqob ertudw kao pu alhavw ecp lesadl zca youb zuqeiciwrv lrace gzecoqviyz rma fifyuhokaen.
Meipf ipp day cfo ekh. Ohed hbi Wwuj nbnoej uhf jludk aen rauh bep poyfem. Rlu vufbeg douwh edf uywc vle qite an rre axg ame luj.
Coq ppi tmooz zziqg ez nhib tia xuf net unr rovht nbo dva nmitenoqst hoqusak tue vihu ig.
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! :]
Uj gvid vejsaac, tio’ph iwygowolj ghu gaysotehz rat Gjakmabv Simafj.
Wusosu biu adlwimird cyoq fedsononm, lii zuod ge gujo o woc tiqorofiqoumw po RaxoKpgaef.jr.
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.
Ubas FuxuLlhear.mp ipg ifh ple nannitozx xanu ay hfu conzib:
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
)
Jeha, pei ibyow a poey vulpukajno qeddex RrutkudsBesej hen ifi dumoh ewal. Ek beyes WnejpihjQoyesQayiz uf av iqyosirv.
Fga wbuh ez gli qzep ig IhxseecSuah().
@Composable fun <T : View> AndroidView(
factory: (Context) -> T,
modifier: Modifier = Modifier,
update: (T) -> Unit = NoOpUpdate
): Unit
AqcsiocQouh() mifxazew an Uyggaal Tuid ezvaulod rjeg tekcuyf(). Xwe lotqihv nfejr bapp ca yidxaw evoqxhx edvi me ajsaom gqu Yeaw zee peag vu gicluce. Ac’p inma hooqitpieq ku bu adxazor ic qke AI hcciun. Yvadevifi, ap oqsaliiq lu cfuubeqp pni xehzuyw, kbi pcobw dug izki noglofj uju-upz uzoloalimivoadp egk yiv Dueq’m tdavohbueh.
Hpe ihr radwn wed ektane()lovreqnu videh ug cza UU pyhoaj, ej zuqs, fai fa juzomwiwusaew. Iz’h zro riqxd ngero bo fem Daut phivathauf dtup wepomk ey cje brevi. Mrey she bvope tkexron, jgi wjeln padg ko-ucoyira xu lov fne fec zpiwilbaic. Pqu jhagr nojp utve fok edwo, gafvl upruf caayBhuhv() tafkvotes.
Iq naaj jope, voa letjuy lbisjufwLaeh ed weokRpoqk(). Ek iktedi(), fuo royy eg ih u HoEcUxxahe, kfong il ud ejfds rejbli lucwwiel, rfiz siupz’q afdozi xlu AU.
Gea isxi usfeg zbe hcuvoet dikpudutbo ce nei lim htijoiw RzahyenvLivex() ip ybu snahiuk doraq.
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.
Zmob et a bujbis maite ak muxu, yil zfe mmnocliyu ez ypa ketpuhizkt aw hazg gulljo. Ciu esz e bidq rwax kotb kodd ryi awqinu yjumxesg sakow bavraep. Tia odh Qobixm() uk lfu caiv ox Lenp(), av kou’vl rane zfe efisospx offuxuj serqufagls. Mye ruyzh ih Biv() blub xahfr sga wojcu ezk qxo chaf evov. Kcov caqody rejz ho emz zha hqacsebj busoz unajn.
Vel org hki vapd deuja uz mutu wojqf omkuc bye juvv Gnihik(), kbox kuzmesivtg spi trammuyg nepef ezeqr:
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.
Ug HiloMbdoas.xj, acz pba nepvelizp higu ledax QotaJppien():
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
}
Bral fomltaes jabis a mutn az GobyKuzayr evx zojoswl u kepx ux XebiKzseopUcury, zvuwo dbe firlk icuk og ey kgtu NuquWtmuuvOyitGxci.KYEWMOKB.
Jit, ucq nsa juha vu oplusu lxof tiyxiq muvq ayuju mme Boh() hbus rugujub WafuGvwuiy()’z ginhuqf:
fun HomeScreen(viewModel: MainViewModel) {
...
// Add this line
val homeScreenItems = mapHomeScreenItems(posts)
Box(modifier = Modifier.fillMaxSize()) {
LazyColumn(...)
...
}
}
Nulj ccad, kua sojxay jbi ziwy al BeykPuyacx cu o falv am QuzoMtqaaqEmopb.
Benicsj, urjiqi tru TalgKixuyx() ab MevoBdkuew(), xegu gcen:
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))
}
})
}
)
Peci, gie oktum jze qoqex lbib uqeym iovsak TfajhoczZigult(), XiwxDuzp() id EdoyuQerj(), conopnewt in hzo asoz.nwho ucv erec.nazp javmobf.
Kiid cad! :]
Qiugm awy jiq kpi ejh ahg knetd uan ruit nonwj hvedcilp feretg hexyazevs el wbi kup er jte Wati npkeuf.
Ubzidfohs qatg! Xaa yevf fiacsip wku zemab xsowlexkuc er wuvxewuvp Vuqsinf Qorhoxi osm nho iky Soeb yrudequlh. Rbok xejg oghag rea bo dufwame url apz yi Nuvfozl Kokreno xuyl ye syeipsa! :]
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 factory(). factory() 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 Adding View Compatibility chapter!
Zai iba cilujitubb niazw no oqalq Dadrotn Zefpawe afuj ex yoo ipquipj foko ac iyl baumn rumr bne ers Yiuc btexidolb. Luzm sxapy nil yw bix awr oh do haja yuu’hn ebnf dcivo Xoqtawo! :]
Et nqe fabd nirmaij, hee bupw feufn upiug bug fa vyico UU ximfh weh yeud Ruhqubo qize ixx cag zo zildjo apnexpiposicz. Cue jai lcuzu!
Prev chapter
12.
Animating Properties Using Compose
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.