在Android Jetpack合成的子组件中禁用滑动手势

2exbekwf  于 2023-01-24  发布在  Android
关注(0)|答案(1)|浏览(161)

正如标题中提到的,我想禁用Composable中的滑动手势ExposedDropdownMenuBox
原因是,有时滑动会同时触发Drawer的滑动打开和ExposedDropdownMenuBox,特别是在下拉菜单标题上滑动时。
如何在ExposedDropdownMenuBox上滑动,仅打开抽屉,而不触发下拉菜单?
抽屉和下拉菜单的示例活动:

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyDrawerTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    Body("Android")
                }
            }
        }
    }
}

@Composable
fun Body(name: String) {
    Scaffold(
        drawerContent = {
            Text("Drawer title $name", modifier = Modifier.padding(16.dp))
            Divider()
            // Drawer items
        }
    ) {
        // Screen content
        DropBox()
    }
}

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun DropBox(){
    val options = listOf("Option 1", "Option 2", "Option 3", "Option 4", "Option 5")
    var expanded by remember { mutableStateOf(false) }
    var selectedOptionText by remember { mutableStateOf(options[0]) }

    ExposedDropdownMenuBox(
        expanded = expanded,
        onExpandedChange = {
            expanded = !expanded
        }
    ) {
        TextField(
            readOnly = true,
            value = selectedOptionText,
            onValueChange = { },
            label = { Text("Label") },
            trailingIcon = {
                ExposedDropdownMenuDefaults.TrailingIcon(
                    expanded = expanded
                )
            },
            colors = ExposedDropdownMenuDefaults.textFieldColors()
        )
        ExposedDropdownMenu(
            expanded = expanded,
            onDismissRequest = {
                expanded = false
            }
        ) {
            options.forEach { selectionOption ->
                DropdownMenuItem(
                    onClick = {
                        selectedOptionText = selectionOption
                        expanded = false
                    }
                ) {
                    Text(text = selectionOption)
                }
            }
        }
    }
}

在下拉菜单的标题上滑动会同时打开抽屉和下拉菜单。如屏幕截图所示

yqkkidmi

yqkkidmi1#

自Compose1.4.0-alpha 04以来,这个问题似乎得到了解决,即应用程序在滑动下拉菜单项时不会打开汉堡菜单。
之前,我有一个变通方案,使用菜单偏移量来检查汉堡菜单是否确实处于关闭位置:

if (scaffoldState.drawerState.offset.value == HomeScreenVM.closedMenuOffset) { //Perform task if the burger menu is closed}

closedMenuOffset是静态变量

companion object {
     var closedMenuOffset = 0f
        set(value) {
            if (field > value) field = value
        }
 }

相关问题