5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Jetpack ComposeでAutoSizeTextViewを実装する

Posted at

AndroidViewでは簡単に設定できたことがJetpack Composeでは少し工夫しないと実装できないことがいくつかあったので紹介します。

autoSizeMinTextSize, autoSizeMaxTextSize

autoSizeTextが公式でサポートされていないため、Jetpack Composeへの移行に伴いどのように実装できるか調べました。

.kt
@Composable
fun AutoSizeableText(
    text: String,
    maxTextSize: TextUnit,
    minTextSize: TextUnit,
    modifier: Modifier = Modifier
) {

    var textSize by remember(text) { mutableStateOf(maxTextSize) }

    Text(
        text = text,
        fontSize = textSize,
        maxLines = 1,
        overflow = TextOverflow.Ellipsis,
        modifier = modifier,
        onTextLayout = {
            if (it.hasVisualOverflow && textSize > minTextSize) {
                textSize = (textSize.value - 1.0F).sp
            }
        }
    )
}

hasVisualOverflowでテキストが枠外に溢れているかどうかをBooleanで返し、trueの時はmaxTextSizeから1sp引いて再度hasVisualOverflowをチェックしています。

image.png

autoSizeText

Androd端末のフォントサイズ設定に影響を受けず、フォントサイズを固定する実装は以下の通りです。

.kt
fun TextFont(
    text: String,
    modifier: Modifier = Modifier,
    fontSize: TextUnit = 10.sp
) {
    FloatingActionButton(onClick = { /*TODO*/ }, modifier = modifier) {
        Text(
            text = text,
            fontSize = with(LocalDensity.current) {
                (fontSize.value / fontScale).sp
            },
        )
    }
}

@Preview(showBackground = true, fontScale = 1.0f)
@Preview(showBackground = true, fontScale = 2f)
@Composable
fun PreviewTextFont() {
    TextFont(text = "Button")
}

LocalDensity.currentを使うことで端末のフォントサイズが取得できる(fontScale)ため、fontSizefontScaleで割ってあげています。そうすることで引数で渡したfontSizeが適用されます。

Before After
image.png image.png

参考記事

5
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?