在 Jetpack Compose 中对齐调整大小的 TextField

Aligning a resized TextField in Jetpack Compose

我在为桌面对齐 Jetpack Compose 中已调整大小的 TextField 时遇到问题。当我调整 TextField 的宽度时,TextField 会自动调整到屏幕的中心位置。我试过使用 Modify.Align 但没有成功。

有人可以帮忙吗?这是我的代码

@Composable
fun addSales(sales: Sales,
             actionChangeSales: (sales: Sales) -> Unit,
             actionQuantityInc: (() -> Unit),
             actionItemNameInc: (() -> Unit)){
    Column{
        TextField(
            value = sales.itemName,
            textStyle = TextStyle(color = Color.DarkGray),
            onValueChange = {
                actionChangeSales(Sales(itemName = it))
                actionItemNameInc.invoke()
            },
            label = { Text("Item name")}
        )

        Spacer(modifier = Modifier.height(16.dp))

        OutlinedTextField(
            value = roundQuantity(sales.quantitySold),
            textStyle = TextStyle(color = Color.DarkGray),
            onValueChange = {
                actionChangeSales(Sales(quantitySold = getDoubleFromEditText(it)))
                actionQuantityInc.invoke()
            },
            label = { Text("Quantity")},
            modifier = Modifier.width(120.dp)
        )
    }
}

您必须再次将它们包裹在 Column 中。

伪代码如下

Column(
    horizontalAlignment = Alignment.CenterHorizontally,
    modifier = Modifiler.fillMaxWidth() // needed so it knows the full width to center the content within it
) {
    // This wraps your content and centers it
    
    Column( horizontalAlignment = Alignment.Start ){
        // This wraps and aligns the content to the left/start

        // place your content here
    }
}

作为解决方法,尝试用 Box 包装 OutlinedTextField 并应用 width 修饰符那里:

            Box(modifier = Modifier.width(120.dp)) {
                OutlinedTextField(
                    value = "123456789",
                    textStyle = TextStyle(color = Color.DarkGray),
                    onValueChange = {},
                    label = { Text("Quantity") },
                )
            }