Jetpack Compose for Desktop实现下拉选择框

·  阅读 882

效果如下:

GIF 2021-04-21 22-06-33.gif

感觉这个DropdownMenu还是有点坑,有时候行为有点奇怪,调整布局、绑定state的时候都有点小坑,也没有很多资料可看,反正最后是做出来了。这次分成几个函数来写,函数间用Props传参数和回调函数。

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.size
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp


class Props {
    var expanded = false
    var selectList: MutableList<String> = mutableListOf("0000", "0001", "0002", "0003")
    var text = selectList[0]
    lateinit var callBack: (String, Boolean) -> Unit
}

class Select(props: Props) {
    private var props: Props = props

    @Composable
    fun Root() {
        var props = props
        /**
         * 控制下拉选择框
         */
        var dropExpand by remember { mutableStateOf(props.expanded) }
        //回调函数
        props.callBack = fun(text: String, expand: Boolean) {
            props.text = text
            dropExpand = expand
        }
        var prop by remember { mutableStateOf(props) }

        Column {
            Row {
                SelectedTextBox(prop)
                SelectButton(prop)
            }
            DropdownMenu(
                expanded = dropExpand,
                onDismissRequest = {
                    props.expanded = false
                    props.callBack(props.text, false)
                },
            ) {
                SelectOption(prop)
            }
        }
    }

    @Composable
    fun SelectedTextBox(props: Props) {
        //显示选中的文本
        TextField(
            props.text,
            onValueChange = {
                props.text = it
            },
            readOnly = true,
            modifier = Modifier.size(90.dp, 50.dp)
        )
    }

    @Composable
    fun SelectButton(props: Props) {
        IconButton(onClick = {
            props.callBack(props.text, true)
        }) {
            //下拉按钮
            Icon(Icons.Default.ArrowDropDown, "")
        }
    }

    @Composable
    fun SelectOption(props: Props) {
        for (it in props.selectList) {
            DropdownMenuItem(onClick = {
                props.callBack(it, false)
            }) {
                Text(it)
            }
        }
    }
}
复制代码
分类:
Android
分类:
Android