2023年12月25日月曜日

InlineTextContent を使って Composable のテキスト中にアイコンを表示する

  1. val id = "inlineContent"  
  2.   
  3. val inlineContent = mapOf(  
  4.     Pair(  
  5.         id,  
  6.         InlineTextContent(  
  7.             Placeholder(  
  8.                 width = 1.em,  
  9.                 height = 1.em,  
  10.                 placeholderVerticalAlign = PlaceholderVerticalAlign.AboveBaseline  
  11.             )  
  12.         ) {  
  13.             Icon(imageVector = Icons.Default.OpenInNew, contentDescription = null)  
  14.         }  
  15.     )  
  16. )  
  17.   
  18. Text(  
  19.     text = buildAnnotatedString {  
  20.         append("open here")  
  21.         appendInlineContent(id, "[open in new]")  
  22.     },  
  23.     inlineContent = inlineContent,  
  24.     fontSize = 24.sp,  
  25. )  
PlaceholderVerticalAlign で上下の位置を指定できる。中央揃えにするなら PlaceholderVerticalAlign.TextCenter がよさげ。