android-fragments 如何使用片段管理器从Jetpack Compose中启动片段?

zour9fqk  于 2022-11-13  发布在  Android
关注(0)|答案(1)|浏览(187)

问题是如何启动适当的Activity上下文来获得Fragment Manager?从可组合对象和Fragment之间的互操作性的Angular 来看,这可能吗?

@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
    }
gkn4icbw

gkn4icbw1#

我已经到处搜索了这个问题,但是我没有找到具体的答案。我猜你想做的是把compose和fragment结合起来。在我的例子中,我所做的是创建一个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** {

            }
        }
    }

然后,在Activity中的任何地方,都可以访问supportFragmentManager,可以使用它来执行片段事务。

相关问题