所以我目前正在制作一份调查问卷,并将其水平放置并带有 4 个单选按钮。当前的代码如下所示:
package com.example.jetquestionnaire.ui.theme
import android.widget.RadioButton
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.selection.selectable
import androidx.compose.material3.RadioButton
import androidx.compose.material3.RadioButtonDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
@Composable
fun RadioButtonTest() {
val options = listOf("3", "2", "1", "0")
var selectedOption by remember { mutableStateOf(options[0]) }
val textAboveRadioButtons = listOf(
"High",
"Medium-High",
"Medium-Low",
"Low",
)
//custom colour
val customSelectedColor = Color(0xFF5799FC)
Row(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
horizontalArrangement = Arrangement.SpaceEvenly,
verticalAlignment = Alignment.CenterVertically,
) {
options.zip(textAboveRadioButtons).forEach { (option, textAbove) ->
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.selectable(
selected = (selectedOption == option),
onClick = { selectedOption = option }
)
.padding(8.dp),
) {
Text(
text = textAbove,
modifier = Modifier
.padding(bottom = 5.dp),
)
RadioButton(
selected = (selectedOption == option),
onClick = { selectedOption = option },
colors = RadioButtonDefaults.colors(
selectedColor = customSelectedColor,
unselectedColor = Color.Gray
),
)
Text(
text = option,
modifier = Modifier.padding(top = 5.dp),
)
}
}
}
}
现在的问题是,按钮上方的文本位于“listOf”列表中,我想在 textAboveButtons 中放置更长的文本。但是,当我输入较长的文本时,它会将其他按钮和文本推到右侧并溢出屏幕。我想让它包起来然后放下来。我该如何处理这个问题?
短文本:
长文本:
当空间不足时,文本可组合项将已经包裹其内容。问题是这不适用于第一个文本,因为当它们布局时,它们仍然具有可用的整行。
您需要的是每个文本可组合项在确定其宽度时考虑其他文本。您可以通过应用
weight
修饰符来做到这一点。这将允许所有具有相同重量的兄弟姐妹占据相同的宽度。由于您将每个文本包装在一个列中,因此您必须将权重修改器应用于该列,因为只有这些列是彼此同级的。
您实际指定的权重并不重要,只需确保所有列的权重相同即可。因为它们是在 for 循环中生成的,所以很简单:
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.selectable(
selected = (selectedOption == option),
onClick = { selectedOption = option }
)
.padding(8.dp)
.weight(1f),
) {
// ...
}