簡體   English   中英

如何在 Jetpack Compose 中將 Surface 中的 Item 居中

[英]How to center Item inside Surface in jetpack compose

如何在 jet pack compose 的表面居中放置項目

@Composable
fun RoundedShapeWithIconCenter(
    modifier: Modifier = Modifier,
    parentSize : Dp,
    parentBackgroundColor : Color,
    childPadding : Dp,
    icon : Painter,
    iconSize : Dp,
    iconTint : Color,
    elevation : Dp = 0.dp,
    isTextOrIcon : Boolean = false,
    insideText : String = "",
    insideTextColor : Color = colorResource(id = R.color.black),
    fontSize: TextUnit = 16.sp
) {
    Surface(
        modifier = modifier.size(parentSize),
        shape = RoundedCornerShape(50),
        color = parentBackgroundColor,
        elevation = elevation,
    ) {
        if (isTextOrIcon) {
            CommonText(value = insideText, fontSize = fontSize, color = insideTextColor, textAlign = TextAlign.Center)
        } else {
            Icon(painter = icon, contentDescription = "Back Arrow", modifier = Modifier
                .size(iconSize)
                .padding(childPadding), tint = iconTint)
        }
    }
}


在此處輸入圖像描述

在圖像中,圓形黑色形狀是表面,Go 是表面內的文本。 我想將 Go 文本置於 Surface 的中心。 如果我用圖標替換文本,它會完美居中

提前致謝

為此,我們已將可組合文本對齊到中心,並且我們不能在 Surface 內使用對齊修飾符。 所以我們將把我們的 CommonText 包裹在 Box 周圍,並對接受修飾符的 CommonText 做一點改變。

RoundedShapeWithIconCenter

....
if (isTextOrIcon) {
    Box(modifier = Modifier
        .fillMaxSize(1.0f) // it will fill parent box
        .padding(8.dp)) { // padding will help us to give some margin between our text and parent if text greater then our parent size

            CommonText(
                value = insideText, 
                fontSize = fontSize, 
                color = insideTextColor,
                modifier = Modifier.align(Alignment.Center) // this will help it to align it to box center
            )
        }
}
....

修改后的通用文本

因為我不知道 CommonText Composable 是如何創建的,所以我假設它喜歡跟隨並根據它進行更改。

@Composable
fun CommonText(modifier: Modifier = Modifier, .... ) {
    Text(modifier = modifier, .... )
}

編輯 - 更簡單的版本

....
if (isTextOrIcon) {
    Box(modifier = Modifier
        .fillMaxSize(1.0f) // it will fill parent box
        .padding(8.dp),// padding will help us to give some margin between our text and parent if text greater then our parent size
        contentAlignment = Center) { // contentAlignment will align its content as provided Alignment in our case it's Center

            CommonText(
                value = insideText, 
                fontSize = fontSize, 
                color = insideTextColor
            )
        }
}
....

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM