1、在ComposeUI中加載AndroidView控件
Compose中可以加載AndroidView還是比較簡單的,直接引入AndroidView來加載AndroidView布局文件。
@Composable
fun Greeting(name: String) {
Column {
Text(text = "Hello $name!")
LoadAndroidView(name)
}
}
/**
* Compose中加載AndroidView
*/
@Composable
fun LoadAndroidView(name: String) {
var tvTittle: TextView? = null
AndroidView(factory = {
//加載AndroidView布局。
LayoutInflater.from(it).inflate(R.layout.activity_main, null).apply {
tvTittle = findViewById(R.id.tvTittle)
}
}) {
//更新UI數(shù)據(jù)
tvTittle?.text = name
}
}
factory
參數(shù)主要是用來初始化AndroidView布局,將AndroidView布局通過工廠模式轉(zhuǎn)換成ComposeUI加載到Compose中,只會執(zhí)行一行,第二個回調(diào)函數(shù),主要是用來更新UI數(shù)據(jù),ReCompose
可能會執(zhí)行,所以我么初始化AndroidView的代碼應(yīng)該放在factory
參數(shù)中。
2、在AndroidView中加載ComposeUI
AndroidView中引入ComposeView直接在AndroidView的布局文件中加入androidx.compose.ui.platform.ComposeView
控件,在代碼中初始化ComposeView,調(diào)用setContent
方法,就可以使用ComposeUI了。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/tvTittle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="我是AndroidView" />
<androidx.compose.ui.platform.ComposeView
android:id="@+id/composeView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
class LoadComposeActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<ComposeView>(R.id.composeView).apply {
setContent {
Column {
Text(text = "我是ComposeView")
}
}
}
}
}
3、LiveData數(shù)據(jù)轉(zhuǎn)換成State數(shù)據(jù)
LiveData是JetPack組件的一部分,主要是在AndroidView中用來監(jiān)聽數(shù)據(jù)的變化,并且具有生命感知的,只有在Activity等處于活動才會觸發(fā)數(shù)據(jù)更新。
State
是Compose中特有的用來更新Ui的數(shù)據(jù)框架。比如常用的mutableStateOf
, mutableListStateOf
等。
當(dāng)AndroidView和Compose交互,將會可能涉及到LiveData
和State
數(shù)據(jù)的交換問題。
由于在AndroidView中常用LiveData來進(jìn)行數(shù)據(jù)的訂閱,而在Compose中使用的是Compose特有的mutableStateOf
或者mutableListStateOf
等來進(jìn)行ReCompose
,UI更新,所以當(dāng)同時存在兩者的時候,需要將
LiveData轉(zhuǎn)換成Compose中的State對象,然后才能在Compose中實現(xiàn)訂閱功能。
Compose庫中提供了一個擴(kuò)展函數(shù)來進(jìn)行LiveData
和State
之間進(jìn)行轉(zhuǎn)換:
1、導(dǎo)入runtime-livedata庫
implementation 'androidx.compose.runtime:runtime-livedata:1.2.0'
2、將LiveData數(shù)據(jù)轉(zhuǎn)換成State數(shù)據(jù)
private val tittleLv = MutableLiveData("Android")
private fun initView() {
findViewById<ComposeView>(R.id.composeView).setContent {
val tittle by tittleLv.observeAsState()
Column {
Text(text = tittle.orEmpty(),Modifier.clickable {
tittleLv.value="測試LiveData轉(zhuǎn)換State"
})
}
}
}
調(diào)用observeAsState擴(kuò)展函數(shù)可以將LiveData
對象直接轉(zhuǎn)換成State
對象,在Compose中使用。
上面代碼給Text
加了個點擊事件改變LiveData
數(shù)據(jù),Compose中的文本同步改變是成功的。
需要注意的是,observeAsState函數(shù)只能在Compose方法中調(diào)用。