Jetpack Compose和View的互操作性

1.在Activity或者Fragment中全部使用Compose來搭建UI

Use Compose in Activity
class ExampleActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
 
        setContent { // In here, we can call composables!
            MaterialTheme {
                Greeting(name = "compose")
            }
        }
    }
}
 
@Composable
fun Greeting(name: String) {
    Text(text = "Hello $name!")
}
Use Compose in Fragment
class PureComposeFragment : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return ComposeView(requireContext()).apply {
            setContent {
                MaterialTheme {
                    Text("Hello Compose!")
                }
            }
        }
    }
}

在View中使用Compose

ComposeView內(nèi)嵌在Xml中:

一個平平無奇的xml布局文件中加入ComposeView

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
 
    <TextView
        android:id="@+id/hello_world"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello from XML layout" />
 
    <androidx.compose.ui.platform.ComposeView
        android:id="@+id/compose_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
 
</LinearLayout>

使用的時候, 先根據(jù)id查找出來, 再setContent:

class ComposeViewInXmlActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_compose_view_in_xml)
 
        findViewById<ComposeView>(R.id.compose_view).setContent {
            // In Compose world
            MaterialTheme {
                Text("Hello Compose!")
            }
        }
    }
}
動態(tài)添加ComposeView

在代碼中使用addView()來添加View對于ComposeView來說也同樣適用

class ComposeViewInViewActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
 
        setContentView(LinearLayout(this).apply {
            orientation = VERTICAL
            addView(ComposeView(this@ComposeViewInViewActivity).apply {
                id = R.id.compose_view_x
                setContent {
                    MaterialTheme {
                        Text("Hello Compose View 1")
                    }
                }
            })
            addView(TextView(context).apply {
                text = "I'm am old TextView"
            })
            addView(ComposeView(context).apply {
                id = R.id.compose_view_y
                setContent {
                    MaterialTheme {
                        Text("Hello Compose View 2")
                    }
                }
            })
        })
    }
}

這里在LinearLayout中添加了三個child: 兩個ComposeView中間還有一個TextView.

起到橋梁作用的ComposeView是一個ViewGroup, 它本身是一個View, 所以可以混進(jìn)View的hierarchy tree里占位,
它的setContent()方法開啟了Compose世界的大門, 在這里可以傳入composable的方法, 繪制UI.

在Compose中使用View

都用Compose搭建UI了, 什么時候會需要在其中內(nèi)嵌View呢?

1.要用的View還沒有Compose版本, 比如AdView, MapView, WebView.
2.有一塊之前寫好的UI, (暫時或者永遠(yuǎn))不想動, 想直接用.
3.用Compose實現(xiàn)不了想要的效果, 就得用View.

在Compose中加入Android View
@Composable
fun CustomView() {
    val state = remember { mutableStateOf(0) }
 
    //widget.Button
    AndroidView(
        factory = { ctx ->
            //Here you can construct your View
            android.widget.Button(ctx).apply {
                text = "My Button"
                layoutParams = LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT)
                setOnClickListener {
                    state.value++
                }
            }
        },
        modifier = Modifier.padding(8.dp)
    )
    //widget.TextView
    AndroidView(factory = { ctx ->
        //Here you can construct your View
        TextView(ctx).apply {
            layoutParams = LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT)
        }
    }, update = {
        it.text = "You have clicked the buttons: " + state.value.toString() + " times"
    })
}

這里的橋梁是AndroidView, 它是一個composable方法:

@Composable
fun <T : View> AndroidView(
    factory: (Context) -> T,
    modifier: Modifier = Modifier,
    update: (T) -> Unit = NoOpUpdate
)

factory接收一個Context參數(shù), 用來構(gòu)建一個View.
update方法是一個callback, inflate之后會執(zhí)行, 讀取的狀態(tài)state值變化后也會被執(zhí)行.

在Compose中使用xml布局

上面提到的在Compose中使用AndroidView的方法, 對于少量的UI還行.
如果需要復(fù)用一個已經(jīng)存在的xml布局怎么辦?
不用怕, view binding登場了.

使用起來也很簡單:

1.首先你需要開啟View Binding.

buildFeatures {
    compose true
    viewBinding true
}

2.其次你需要一個xml的布局, 比如叫complex_layout.
3.然后添加一個Compose view binding的依賴: androidx.compose.ui:ui-viewbinding.

然后build一下, 生成binding類,
這樣就好了

@Composable
private fun ComposableFromLayout() {
    AndroidViewBinding(ComplexLayoutBinding::inflate) {
        sampleButton.setBackgroundColor(Color.GRAY)
    }
}

其中ComplexLayoutBinding是根據(jù)布局名字生成的類.

AndroidViewBinding內(nèi)部還是調(diào)用了AndroidView這個composable方法.

在Compose中顯示Fragment

這個場景聽上去有點奇葩, 因為Compose的設(shè)計理念, 貌似就是為了跟Fragment說再見.
在Compose構(gòu)建的UI中, 再找地方顯示一個Fragment, 有點新瓶裝舊酒的意思.

但是遇到的場景多了, 你沒準(zhǔn)真能遇上呢.

Fragment通過FragmentManager添加, 需要一個布局容器.
把上面ViewBinding的例子改改, 布局里加入一個fragmentContainer, 點擊顯示Fragment:

Column(Modifier.fillMaxSize()) {
    Text("I'm a Compose Text!")
    Button(
        onClick = {
            showFragment()
        }
    ) {
        Text(text = "Show Fragment")
    }
    ComposableFromLayout()
}
 
@Composable
private fun ComposableFromLayout() {
    AndroidViewBinding(
        FragmentContrainerBinding::inflate,
        modifier = Modifier.fillMaxSize()
    ) {
 showFragment()
    }
}
 
private fun showFragment() {
    supportFragmentManager
        .beginTransaction()
        .add(R.id.fragmentContainer, PureComposeFragment())
        .commit()
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末强饮,一起剝皮案震驚了整個濱河市唆铐,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖历涝,帶你破解...
    沈念sama閱讀 217,277評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件兰迫,死亡現(xiàn)場離奇詭異,居然都是意外死亡秧廉,警方通過查閱死者的電腦和手機(jī)伞广,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評論 3 393
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來疼电,“玉大人嚼锄,你說我怎么就攤上這事”尾颍” “怎么了区丑?”我有些...
    開封第一講書人閱讀 163,624評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長修陡。 經(jīng)常有香客問我沧侥,道長,這世上最難降的妖魔是什么濒析? 我笑而不...
    開封第一講書人閱讀 58,356評論 1 293
  • 正文 為了忘掉前任正什,我火速辦了婚禮,結(jié)果婚禮上号杏,老公的妹妹穿的比我還像新娘婴氮。我一直安慰自己斯棒,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,402評論 6 392
  • 文/花漫 我一把揭開白布主经。 她就那樣靜靜地躺著荣暮,像睡著了一般。 火紅的嫁衣襯著肌膚如雪罩驻。 梳的紋絲不亂的頭發(fā)上穗酥,一...
    開封第一講書人閱讀 51,292評論 1 301
  • 那天,我揣著相機(jī)與錄音惠遏,去河邊找鬼砾跃。 笑死,一個胖子當(dāng)著我的面吹牛节吮,可吹牛的內(nèi)容都是我干的抽高。 我是一名探鬼主播,決...
    沈念sama閱讀 40,135評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼透绩,長吁一口氣:“原來是場噩夢啊……” “哼翘骂!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起帚豪,我...
    開封第一講書人閱讀 38,992評論 0 275
  • 序言:老撾萬榮一對情侶失蹤碳竟,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后狸臣,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體莹桅,經(jīng)...
    沈念sama閱讀 45,429評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,636評論 3 334
  • 正文 我和宋清朗相戀三年烛亦,在試婚紗的時候發(fā)現(xiàn)自己被綠了统翩。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,785評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡此洲,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出委粉,到底是詐尸還是另有隱情呜师,我是刑警寧澤,帶...
    沈念sama閱讀 35,492評論 5 345
  • 正文 年R本政府宣布贾节,位于F島的核電站汁汗,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏栗涂。R本人自食惡果不足惜知牌,卻給世界環(huán)境...
    茶點故事閱讀 41,092評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望斤程。 院中可真熱鬧角寸,春花似錦菩混、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至亿柑,卻和暖如春邢疙,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背望薄。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評論 1 269
  • 我被黑心中介騙來泰國打工疟游, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人痕支。 一個月前我還...
    沈念sama閱讀 47,891評論 2 370
  • 正文 我出身青樓颁虐,卻偏偏與公主長得像,于是被迫代替她去往敵國和親采转。 傳聞我的和親對象是個殘疾皇子聪廉,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,713評論 2 354

推薦閱讀更多精彩內(nèi)容