Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Styling Text with Jetpack Compose

Styling Text with Jetpack Compose

Avatar for Tsuyoshi UEHARA

Tsuyoshi UEHARA

July 10, 2020
Tweet

More Decks by Tsuyoshi UEHARA

Other Decks in Programming

Transcript

  1. その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
  2. その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
  3. 7

  4. その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
  5. その3: テキスト内にカスタム絵⽂字(画像)を表⽰ 2/3 inlineContent: Map<String, InlineTextContent> を定義して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
  6. その3: テキスト内にカスタム絵⽂字(画像)を表⽰ 2/3 CustomEmojiImageは普通にImageを表⽰するだけ @Composable fun CustomEmojiImage(imageResId: Int) { Image(

    modifier = Modifier.fillMaxSize(), asset = vectorResource(id = imageResId), contentScale = ContentScale.FillWidth ) } 10