這就是我想要實作的目標:

因此,我連續創建了 2 個圓形按鈕,并根據它們是否被選中提供不同的背景顏色。目標是創建一種選項卡/切換的錯覺。
未選中的按鈕將具有與行的背景顏色相同的顏色。不幸的是,由于一行是矩形,所以在角落處有一個殘留空間,仍然顯示背景顏色。


這是我的按鈕代碼
val cornerRadius = 20.dp
var selectedIndex by remember { mutableStateOf(0)}
val configuration = LocalConfiguration.current
val screenWidth = configuration.screenWidthDp.dp
val items = listOf(
OutlinedButton(onClick = { /*TODO*/ }) {
},
OutlinedButton(onClick = { /*TODO*/ }) {
})
Row(
modifier = Modifier
.padding(top = 8.dp)
.wrapContentHeight()
.width(screenWidth).background(color = Color.Gray).clip(shape = RoundedCornerShape(20.dp))
) {
// Spacer(modifier = Modifier.weight(1f))
items.forEachIndexed { index, item ->
OutlinedButton(modifier = Modifier
.wrapContentHeight()
.width(screenWidth/2),
shape = when (index) {
// left outer button
0 -> (if (selectedIndex == index) {
RoundedCornerShape(
topStart = cornerRadius,
topEnd = cornerRadius,
bottomStart = cornerRadius,
bottomEnd = cornerRadius
)
} else {
RoundedCornerShape(
topStart = cornerRadius,
topEnd = cornerRadius,
bottomStart = cornerRadius,
bottomEnd = cornerRadius
)
})
//rightouterbutton
else -> (if (selectedIndex == index) {
RoundedCornerShape(
topStart = cornerRadius,
topEnd = cornerRadius,
bottomStart = cornerRadius,
bottomEnd = cornerRadius
)
}
else{RoundedCornerShape(
topStart = 0.dp,
topEnd = cornerRadius,
bottomStart = 0.dp,
bottomEnd = cornerRadius
)})
},
border = BorderStroke(
1.dp, if (selectedIndex == index) {
Color.Transparent
} else {
Color.Transparent
}
),
colors = if (selectedIndex == index) {
// colors when selected
ButtonDefaults.outlinedButtonColors(
backgroundColor = Color.Yellow,
contentColor = Color.Black
)
} else {
// colors when not selected
ButtonDefaults.outlinedButtonColors(
backgroundColor = Color.Gray,
contentColor = Color.Black
)
},
onClick = { selectedIndex = index },
) {
if (index == 0) {
Text(
text = "In progress",
color = if (selectedIndex == index) {
Color.Black
} else {
Color.DarkGray.copy(alpha = 0.9f)
},
modifier = Modifier.padding(horizontal = 8.dp)
)
} else {
Text(
text = "Completed",
color = if (selectedIndex == index) {
MaterialTheme.colors.primary
} else {
Color.DarkGray.copy(alpha = 0.9f)
},
modifier = Modifier.padding(horizontal = 8.dp)
)
}
}
}
}
uj5u.com熱心網友回復:
Modifier.clip在對您的情況沒有影響之后應用Modifier.background,您需要顛倒順序。閱讀更多關于為什么修飾符的順序在這個答案中很重要
.clip(shape = RoundedCornerShape(20.dp))
.background(color = Color.Gray)
在這種情況下的另一個選擇Modifier.background是您可以將形狀專門應用于背景顏色。請注意,此解決方案不會將其他視圖內容剪輯到形狀Modifier.clip中,但在您的情況下它適合。
.background(color = Color.Gray, shape = RoundedCornerShape(20.dp))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/433942.html
標籤:用户界面 按钮 排 android-jetpack-compose
