日期选择器安装座和年份喷气背包组成

问题描述 投票:0回答:1

我怎样才能使打开日历时,用户只能选择jetpack compose中的月份和年份。我在文档中没有找到这样的方法。

我尝试以某种方式更改日期选择器,但它不起作用,我想我需要创建自己的日期选择器,但我真的不想这样做。

android kotlin datepicker android-jetpack-compose material-design
1个回答
0
投票

以下是有关如何在 Jetpack Compose 中实现此功能的基本想法

月份选择:使用下拉菜单或月份列表进行选择。

年份选择:使用可滚动列或滑块让用户选择年份

  @Composable
fun MonthYearPicker(
    selectedMonth: String,
    selectedYear: Int,
    onMonthSelected: (String) -> Unit,
    onYearSelected: (Int) -> Unit,
    currentYear: Int = 2024,
    yearRange: IntRange = (1900..currentYear)
) {
    var expanded by remember { mutableStateOf(false) }
    val months = listOf(
        "January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December"
    )

    Column {`enter code here`
        // Month Picker
        ExposedDropdownMenuBox(
            expanded = expanded,
            onExpandedChange = { expanded = !expanded }
        ) {
            TextField(
                value = selectedMonth,
                onValueChange = {},
                readOnly = true,
                label = { Text("Select Month") },
                trailingIcon = {
                    Icon(Icons.Filled.ArrowDropDown, null)
                }
            )
            ExposedDropdownMenu(
                expanded = expanded,
                onDismissRequest = { expanded = false }
            ) {
                months.forEach { month ->
                    DropdownMenuItem(onClick = {
                        onMonthSelected(month)
                        expanded = false
                    }) {
                        Text(text = month)
                    }
                }
            }
        }

        // Year Picker
        LazyColumn(
            modifier = Modifier.height(200.dp) // Set an appropriate height
        ) {
            items(yearRange.toList()) { year ->
                Text(
                    text = year.toString(),
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(8.dp)
                        .clickable { onYearSelected(year) }
                )
            }
        }
    }}
© www.soinside.com 2019 - 2024. All rights reserved.