Jetpack撰写-居中文本

时间:2020-09-03 07:46:24

标签: android android-layout kotlin android-jetpack-compose

我正在使用Jetpack Compose创建一个简单的闪存卡。 这个想法是您单击闪存卡,它将为您提供答案。 但是,我陷入了一个基本问题。

不幸的是...我什至找不到官方文档,所以我的学习风格一直信任自动更正系统...

无论如何,我认为问题出在Box()还是Text()上。 我为框的重力添加了Align.CenterEnd。但是,这似乎是使框居中居中的唯一方法。另一方面,Text()没有提供任何方法(具有重力,但似乎没有任何改变)

向正确方向伸出援助之手会很棒。

另一方面,我知道这将提供免费答案。但是,我该如何在点击时更改$ question的文本。正如我认为Composables刷新一样?...,是否应该在屏幕上重新生成?也许不是吗?

谢谢!

 val typography = MaterialTheme.typography

        val context = ContextAmbient.current
        var question = "How many Bananas should go in my Smoothie?"


        Column(modifier = Modifier.padding(30.dp).then(Modifier.fillMaxWidth())
                .then(Modifier.wrapContentSize(Alignment.Center))
                .clickable(onClick = { Toast.makeText(context, "3 Bananas are needed!", Toast.LENGTH_LONG).show()} ) /*question = "3 Bananas required"*/
                .clip(shape = RoundedCornerShape(16.dp))) {
            Box(modifier = Modifier.preferredSize(350.dp)
                    .gravity(align = Alignment.CenterHorizontally)
                    .border(width = 4.dp, color = Gray, shape = RoundedCornerShape(16.dp)),
            shape = RoundedCornerShape(2.dp),
            backgroundColor = DarkGray,
            gravity = Alignment.CenterEnd) {
                Text("$question",
                style = typography.h4,
                )
            }
        }

Picture of Current Content

1 个答案:

答案 0 :(得分:3)

您可以在Text中应用textAlign = TextAlign.Center

Column(modifier = Modifier
            .padding(30.dp)
            .fillMaxWidth()
            .wrapContentSize(Alignment.Center)
            .clickable(onClick = { } ) /*question = "3 Bananas required"*/
            .clip(shape = RoundedCornerShape(16.dp)),
) {
    Box(modifier = Modifier
            .preferredSize(350.dp)
            .border(width = 4.dp, color = Gray, shape = RoundedCornerShape(16.dp)),
             alignment = Alignment.Center) {
        Text("Question 1 : How many cars are in the garage?",
                Modifier.padding(16.dp),
                textAlign = TextAlign.Center,
                style = typography.h4,
        )

enter image description here

关于文字。

您可以使用类似的内容:

var text by remember { mutableStateOf(("How many cars are in the garage?")) }

在您的可点击项目中:

.clickable(onClick = { text= "After clicking"} )

在您的文本中:

  Text(text, 
        textAlign = TextAlign.Center,
        ...)

这很简单。可以使用动态结构代替静态String来存储和更新值。