![](/img/trans.png)
[英]Navigate from Jetpack Compose to Fragment and from Fragment to Jetpack Compose Screen
[英]How to launch a Fragment from within Jetpack Compose with Fragment Manager?
问题是如何获得正确的活动上下文来启动以获取片段管理器? 从 Composables 和 Fragment 之间的互操作性的角度来看,这甚至可能吗?
@Keep
class Card @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null
) : FrameLayout( // or any other View you want
// don't forget to use context wrapper and to apply your own theme
ContextThemeWrapper(
context,
context.resources.newTheme().apply { applyStyle(R.style.FantasyTheme, true) }
),
attrs
), GamingHubView {
override fun initialize(data: Map<String, Any>?) {
// inflate a view or render views dynamically
// inflate(context, R.layout.view_card, this)
val transaction: FragmentTransaction =
(this.context as AppCompatActivity).supportFragmentManager.beginTransaction()
transaction.replace(
this.id,
BlankFragment.newInstance("", ""),
BlankFragment::class.simpleName
)
transaction.addToBackStack(null)
transaction.commit()
}
}
/**
* Get activity instance from desired context.
*/
fun getActivity(context: Context?): AppCompatActivity? {
if (context == null) return null
if (context is AppCompatActivity) return context
return if (context is ContextWrapper) getActivity(context.baseContext) else null
}
我到处都在搜索这个,但我找不到那个具体的答案。 我猜你想要做的是结合撰写和片段。 我在我的案例中所做的是创建了一个 MyActivity ,它有一个像这样填充整个屏幕的 compose 视图
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MyActivity">
<androidx.compose.ui.platform.ComposeView
android:id="@+id/compose_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
然后在 MyActivity onCreate 方法中,像这样实例化您的撰写视图
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_capture)
findViewById<ComposeView>(R.id.compose_view).setContent {
**YourTheme** {
}
}
}
然后在您的活动中的任何地方,您都可以访问supportFragmentManager
,您可以使用它来执行片段事务。 所有 compose function 都将在composeView.setContent { }
您可以使用以下行从 compose function 中获取对活动的引用:
val activity = LocalContext.current as? AppCompatActivity ?: return
然后您可以获得支持片段管理器并从您的撰写代码中执行片段事务。
activity.supportFragmentManager.commit {
...
}
我认为这不符合 compose 的全部精神,但如果您有一个混合片段/撰写应用程序,那么我看不出这样做有什么害处。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.