Slide 1

Slide 1 text

Jetpack Composeでテキストを装飾する話 Potatotips #70 Tsuyoshi Uehara 1

Slide 2

Slide 2 text

⾃⼰紹介 お名前: Tsuyoshi Uehara Twitter: @uecchi Github: @tsuyosh 2

Slide 3

Slide 3 text

今回のお題 Jetpack Composeで装飾つきのテキストを表⽰する 3

Slide 4

Slide 4 text

Jetpack Composeとは? Googleで絶賛開発中のAndroidの新しいUI Toolkit 全てKotlinで実装 宣⾔的にUIを構築することができる 最新バージョンは0.1.0-dev14 Android Studio 4.2 Canary簡単に試せます 4

Slide 5

Slide 5 text

その1: テキスト全体を装飾 テキスト全体にスタイルを適⽤する場合はText関数の引数に渡す @Composable fun StyledGreeting(name: String) { Text( text = "Hello $name!", color = Color.Green, fontSize = 30.sp, fontFamily = FontFamily.Cursive, fontStyle = FontStyle.Italic, fontWeight = FontWeight.Bold ) } 5

Slide 6

Slide 6 text

その2: テキストの⼀部を装飾 テキストの⼀部を装飾したい場合、AnnotatedStringクラスを使います. 従来のFrameworkではSpannedに相当 @Composable fun StyledGreeting2(name: String) { val greetingText = annotatedString { pushStyle(SpanStyle(color = Color.Green)) append("Hello ") // 前にpush したstyle は引き継がれる pushStyle(SpanStyle( fontSize = 40.sp, // Snip fontFamily, fontStyle, fontWeight fontSynthesis = FontSynthesis.All, textDecoration = TextDecoration.Underline )) append("$name!") pop() // 直近でpush したstyle はpop できる } Text(text = greetingText, fontSize = 30.sp) } 6

Slide 7

Slide 7 text

7

Slide 8

Slide 8 text

その3: テキスト内にカスタム絵⽂字(画像)を表⽰ 1/3 従来のImageSpanの様にテキスト内にカスタム絵⽂字(画像)を表⽰したい場合は InlineTextContentクラスを使います。 @Composable fun StyledGreeting3(name: String) { val inlineContentId = "InlineContent" val greetingText = annotatedString { append("Hello $name!") // inline content を挿⼊ appendInlineContent(id = inlineContentId, alternateText = ":droid:") } // snip } 8

Slide 9

Slide 9 text

その3: テキスト内にカスタム絵⽂字(画像)を表⽰ 2/3 inlineContent: Map を定義してText関数に渡します。 @Composable fun StyledGreeting3(name: String) { val inlineContentId = "InlineContent" val greetingText = // snip val inlineContent = mapOf( inlineContentId to InlineTextContent( Placeholder( width = 30.sp, height = 30.sp, placeholderVerticalAlign = PlaceholderVerticalAlign.Center ) ) { alternateText -> // このlambda はComposable 関数 CustomEmojiImage(imageResId = R.drawable.ic_android_robot) } ) Text(text = greetingText, fontSize = 30.sp, inlineContent = inlineContent) } 9

Slide 10

Slide 10 text

その3: テキスト内にカスタム絵⽂字(画像)を表⽰ 2/3 CustomEmojiImageは普通にImageを表⽰するだけ @Composable fun CustomEmojiImage(imageResId: Int) { Image( modifier = Modifier.fillMaxSize(), asset = vectorResource(id = imageResId), contentScale = ContentScale.FillWidth ) } 10

Slide 11

Slide 11 text

まとめ Text関数でテキスト全体のスタイルを指定できる AnnotatedStringでテキストの⼀部を装飾できる InlineTextContentで画像やカスタム絵⽂字もテキスト内で表⽰できる(⼀番欲しかったも の) サンプルコードはこちら https://github.com/tsuyosh/JetpackComposeTextDemo 11

Slide 12

Slide 12 text

Thank you for listening 12

Slide 13

Slide 13 text

References Jetpack Compose(Youtubeの動画) Exploring Jetpack Compose: Text 13