onValueChange() 未使用自定义键盘 Jetpack compose 调用

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

我正在创建一个 GST 计算器。为此,设计了一个自定义键盘。无论在键盘中按下哪个键,都必须更新 TextField() 中的值。这工作正常。

现在,我希望如果用户输入任何带有 +、-、* 等算术符号的值,那么它会自动开始像计算器应用程序中那样进行计算。这与基本 Android 编程中使用的 EditText() 中的 TextWatcher() 类似。

下面是我迄今为止尝试过的代码。

@Composable
fun MyEditTextField(inputValue: String, onValueChange: (String) -> Unit) {
    var textState by remember { mutableStateOf(TextFieldValue(text = inputValue)) }

    Column {
        BasicTextField(
            value = textState.text,
            onValueChange = {
                textState = TextFieldValue(text = it)
                onValueChange(it)
            },
            singleLine = true
        )
        OutputTextView(text = textState.text)
    }
}

@Composable
fun OutputTextView(text: String) {
    Text(text = text)
}

这段代码的调用是

val tvCalculator = remember { mutableStateOf("") }
MyEditTextField(inputValue =tvCalculator.value )
        {
            Log.d("TAG", "inputValue" + it)
        }

在上面的代码中 onValueChange(it) 没有调用。

附注这是一个只读的 TextField()

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

您可以更新 MyEditTextField 可组合项内的逻辑来解析输入字符串并相应地执行计算。

 @Composable
    fun MyEditTextField(inputValue: String, onValueChange: (String) -> Unit) {
        var textState by remember { mutableStateOf(TextFieldValue(text = inputValue)) }
    
        Column {
            BasicTextField(
                value = textState.text,
                onValueChange = {
                    val newText = handleInputTextChange(textState.text.text, it)
                    textState = TextFieldValue(text = newText)
                    onValueChange(newText)
                },
                singleLine = true
            )
            OutputTextView(text = textState.text.text)
        }
    }

private fun handleInputTextChange(currentText: String, newText: String): String {
    // Append the new text to the current text
    val updatedText = currentText + newText
    
    // Check if the updated text ends with an arithmetic symbol
    if (updatedText.matches(Regex(".*[+\\-*/]$"))) {
        // If it ends with an arithmetic symbol, perform calculation
        return performCalculation(updatedText)
    }
    
    // Otherwise, return the updated text as is
    return updatedText
}

private fun performCalculation(expression: String): String {
}
© www.soinside.com 2019 - 2024. All rights reserved.