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!”)
}
}
}
}
}
ComposeView内嵌在Xml中:
一个平平无奇的xml布局文件中加入ComposeView
:
<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” />
使用的时候, 先根据id查找出来, 再setContent:
class ComposeViewInXmlActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_compose_view_in_xml)
findViewById(R.id.compose_view).setContent {
// In