我正在将一个片段从旧的Jetpack迁移到Jetpack Compose。此片段是现有导航图的一部分。
迁移片段(使用ComposeView)进行合成后,片段方向不再可用。
这种情况下你会怎么做?片段是导航图一部分,几个未组合的片段导航到它。
以下是片段的 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导航图,您仍然必须使用Fra(片段)。但是,片段用于膨胀其根的布局可以只有一个填充xml布局的ComposeView。我可以想象您可以利用AbstractComposeView
做这样的事情:
片段的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>
然后是您的自定义组合视图代码:
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
}
}