Android - AnnotatedString

HEETAE HEO·2023년 2월 4일
0
post-thumbnail

개요

입사 4개월 차인 저는 오늘도 개발을 하고 있었습니다. UI 부분(Compose)을 작업할 때 문제가 발생했었습니다. BottomSheete안에서 문자가 너무 길어져 텍스트 다음 부분에서 생성되어야할 부분이 생기지가 않는 것 입니다. 레이아웃 인스펙터로 확인해본 결과 텍스트의 영역이 할당된 영역 전체를 가지게 되었고 Image는 생성될 공간이 없어 뒷 쪽으로 밀려나는 현상이 발생하였습니다. (ex - 텍스트가 한 줄을 넘어가니 Text가 끝나는 지점까지 있지 않더라도 영역을 차지해 Image가 생성될 공간이 없었습니다.) 그래서 찾아본 결과 AnnotatedString 이라는 것을 찾았습니다.

AnnotatedString 이란??

Android 공식문서에는 다음과 같이 작성되어 있습니다.

The basic data structure of text with multiple styles

여러 구조들이 있는 텍스트의 기본 데이터라고 적혀있습니다.

추가적으로 설명하자면 AnnotatedString은 하나의 Text 안에서 여러 스타일을 적용할 수 있도록 하는 정보를 담은 객체입니다.

AnnotatedString은 buildAnnotatedString을 통해 만들 수 있습니다.

제가 해결한 방법은 다음과 같습니다. 바로 코드로 넘어가 설명하겠습니다.

Text Composable중 다음과 같은 Composable이 있습니다.

@Composable
fun Text(
    text: AnnotatedString,
    modifier: Modifier = Modifier,
    color: Color = Color.Unspecified,
    fontSize: TextUnit = TextUnit.Unspecified,
    fontStyle: FontStyle? = null,
    fontWeight: FontWeight? = null,
    fontFamily: FontFamily? = null,
    letterSpacing: TextUnit = TextUnit.Unspecified,
    textDecoration: TextDecoration? = null,
    textAlign: TextAlign? = null,
    lineHeight: TextUnit = TextUnit.Unspecified,
    overflow: TextOverflow = TextOverflow.Clip,
    softWrap: Boolean = true,
    maxLines: Int = Int.MAX_VALUE,
    inlineContent: Map<String, InlineTextContent> = mapOf(),
    onTextLayout: (TextLayoutResult) -> Unit = {},
    style: TextStyle = LocalTextStyle.current
)

이 Text에 맨 위를 보면 text 값을 넣어주는 부분에 타입이 AnnotatedString으로 되어 있습니다. 누가봐도 AnnotatedString으로 넣어주라는 의미입니다.

그리고 사용할 것은 inlineContent 입니다.
바로 코드 작성으로 가겠습니다.

val annotatedString = buildAnnotatedString {
    append("이렇게 하면 String에 Image를 추가할 수 있습니다.")
    appendInlineContent(id = "imageId")
}
val inlineContentMap = mapOf(
    "imageId" to InlineTextContent(
        Placeholder(20.dpToSp(), 20.dpToSp(), PlaceholderVerticalAlign.TextCenter)
    ) {
        Image(
            painter = painterResource(R.drawable.name),
           contentDescription = "이미지 입니다!",
           modifier = Modifier
             )
    }
)

Text(
    text = annotatedString,
    inlineContent = inlineContentMap
)

다음과 같이 작성하게되면

이렇게 나오게 되며 text 중간에도 넣을 수 있습니다.

val annotatedString = buildAnnotatedString {
    append("이렇게 하면 String에)
    appendInlineContent(id = "imageId")
    append("Image를 추가할 수 있습니다.")
}

뒤에 append를 추가해주면

이렇게 Text중간에 Image가 들어가있는 Text를 만들 수 있습니다.

AnnotatedString의 경우 유용하게 쓰일 수 있을 거 같다라는 생각이 들며 여기까지 작성해보도록 하겠습니다. 읽어주셔서 감사합니다!!!

References

https://developer.android.com/reference/kotlin/androidx/compose/ui/text/AnnotatedString

profile
Android 개발 잘하고 싶어요!!!

0개의 댓글