LoginSignup
0
0

More than 1 year has passed since last update.

JetpackComposeでタップしている間だけテキストの色が変わる方法

Posted at

JetpackComposeでタップしている間だけテキストの色が変わる方法の簡単なサンプルを紹介いたします。

実装サンプル

ClickText.kt
@Composable
fun ClickText(
    modifier: Modifier = Modifier,
    onClick: () -> Unit = {},
    text: String,
    interactionSource: MutableInteractionSource =
        remember { MutableInteractionSource() }
) {
    val isLinkTextPressed by interactionSource.collectIsPressedAsState()
    Text(
        modifier = modifier
            .clickable(
                onClick = { onClick.invoke() },
                indication = null,
                interactionSource = interactionSource
            ),
        text = text,
        style = Typography().body2.copy(
            color = if (isLinkTextPressed) {
                Color(0x8000FF00)
            } else {
                Color(0xFF00FF00)
            }
        )
    )
}

interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }

操作の状態に関する物です。詳しくはリファレンスにあります。

val isLinkTextPressed by interactionSource.collectIsPressedAsState()
今回はタップされて居るかどうかなのでcollectIsPressedAsStateを使用します。

あとはModifierのclickableに設定します。
その後isLinkTextPressedの状態を見てカラーを設定すれば終わります。

リファレンス

0
0
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
0
0