首页 > 解决方案 > 如何在 Jetpack Compose 中使用小部件?

问题描述

我想使用其中的一些,但我从NumberPickerwhich extends开始LinearLayout,因此不能只在视图中间实例化一个实例。当然,只需要一个嵌入式数字微调器作为输入值的一种方式。

标签: androidandroid-widgetandroid-jetpack-compose

解决方案


您现在可以在 Compose中为尚未为其创建特定可组合项的每个小部件使用Android 视图。

@Composable
fun CustomView() {
    val selectedItem = remember { mutableStateOf(0) }

    // Adds view to Compose
    AndroidView(
        modifier = Modifier.fillMaxSize(), // Occupy the max size in the Compose UI tree
        factory = { context ->
            // Creates custom view
            CustomView(context).apply {
                // Sets up listeners for View -> Compose communication
                myView.setOnClickListener {
                    selectedItem.value = 1
                }
            }
        },
        update = { view ->
            // View's been inflated or state read in this block has been updated
            // Add logic here if necessary

            // As selectedItem is read here, AndroidView will recompose
            // whenever the state changes
            // Example of Compose -> View communication
            view.coordinator.selectedItem = selectedItem.value
        }
    )
}

推荐阅读