在 Jetpack Compose 中使用自定义视图

Joa*_*huk 4 android android-jetpack-compose

假设我正在使用一些旨在提供一些 UI 小部件的库。假设这个库提供了一个名为 的按钮小部件FancyButton

另一方面,我有一个使用 Android Studio 4 创建的新项目,它允许我创建一个带有Empty Compose Activity.

问题是: 我应该如何将它添加FancyButton到视图堆栈中?是否可以?或者,对于 Jetpack Compose,我只能使用专为 Jetpack Compose 开发的组件。在这种情况下,据我所知,我只能使用Android组件执行标准(TextMaterialTheme,等)。

如果我尝试使用这样的东西:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
        MaterialTheme {
            Greeting("Android")
            FancyButton(context, "Some text")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我收到这个错误:

e: Supertypes of the following classes cannot be resolved. Please make sure you have the required dependencies in the classpath.

Rya*_*ley 5

目前(截至0.1.0-dev04),对此没有好的解决方案。将来,您可以简单地将其称为FancyButton("Some text")context不需要)。

您可以在此处查看 Compose 代码中的演示。


Mah*_*alv 1

更新于alpha 06

可以在可组合项中导入Android View实例。

用作视图的参数ContextAmbient.currentcontext

Column(modifier = Modifier.padding(16.dp)) {

    // CustomView using Object
    MyCustomView(context = ContextAmbient.current)

    // If the state updates
    AndroidView(viewBlock = ::CustomView, modifier = modifier) { customView ->
        // Modify the custom view
    }

    // Using xml resource
    AndroidView(resId = R.layout.view_demo)
}

Run Code Online (Sandbox Code Playgroud)