你能用旧的导航图和喷气背包组合吗



我正在将一个片段从旧的Jetpack迁移到Jetpack Compose。这个片段是现有导航图的一部分。

将片段(使用ComposeView(迁移到Compose后,片段方向将不再可用。

在这种情况下你会怎么做?片段是导航图的一部分,几个非合成片段导航到它

以下是片段的onCreateView:

override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
) = ComposeView(requireContext()).apply {
setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
setContent {
val surface = ThemeUtils.getColor(context, getBackgroundColor())
val primaryText = ThemeUtils.getColor(context, R.attr.textColorPrimary)
val secondaryText = ThemeUtils.getColor(context, R.attr.userEducationButtonTextColor)
val userEducationFragmentButtonColor = ThemeUtils.getColor(context, R.attr.userEducationButtonColor)
val colors = MaterialTheme.colors.copy(
surface = Color(surface),
primary = Color(ThemeUtils.getPrimaryColor(context)),
onPrimary = Color(primaryText),
onSecondary = Color(secondaryText),
secondary = Color(userEducationFragmentButtonColor),
)
MaterialTheme(colors) {
UserEducationScreen(
title = viewModel.title,
subtext = viewModel.subtext,
backgroundIconUrl = viewModel.backgroundIconUrl,
backgroundImage = viewModel.backgroundImage,
imageUrl = viewModel.imageUrl,
showIconImage = viewModel.showIcon,
primaryButtonText = viewModel.primaryButtonText,
primaryButtonClick = viewModel.primaryButtonClick ?: {},
secondaryButtonText = viewModel.secondaryButtonText,
secondaryButtonClick = viewModel.secondaryButtonClick ?: {},
showArrow = viewModel.showArrow,
showSecondaryButton = viewModel.showSecondaryButton,
screenSizePercentage = getScreenPercent(),
screenSize = api.getScreenSize(context)
)
}
}
}

在XML中完成的导航图只支持导航到片段/活动/其他图。如果你想在那里处理可组合的内容,并且仍然使用xml导航图,你仍然需要使用Fragment。但是,片段用来扩展其根的布局可以只具有一个ComposeView来填充xml布局。我想你可以利用AbstractComposeView:做这样的事情

Fragment的xml布局

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<com.my.app.CustomComposeView
android:id="@+id/customView"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

然后您的CustomComposeView代码:

class CustomComposeView @JvmOverloads constructor (
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0,
) : AbstractComposeView(context, attrs, defStyle) {

@Composable
override fun Content() {
// Your compose code for your fragment here
}
}

最新更新