Hanbit the Developer

[Kotlin] Set indent to first line of TextView in android 본문

Mobile/Android

[Kotlin] Set indent to first line of TextView in android

hanbikan 2021. 8. 10. 15:49

 - Description

To do so, you should use Span, LeadingMarginSpan.

In a nutshell, Span is used to set text style in detail, and LeadingMarginSpan is one of the styles that is related to margin, especially can set margins of first and rest separately.

 

First of all, initialize your span which will be assigned to textView.

val spannable = SpannableString(yourTextView.text)

And, define LeadingMarginSpan like below.

val span = LeadingMarginSpan.Standard(50, 0)

The first parameter(50) is indent for first line, and the seconds is for rest lines.

 

Next, use setSpan() to apply LeadingMarginSpan to Span like this.

spannable.setSpan(span, 0, spannable.count(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

Finally assign Span to textView!

yourTextView.text = spannable

 

 - Code

The integrated codes is as follows.

val spannable = SpannableString(yourTextView.text)
val span = LeadingMarginSpan.Standard(50, 0)
spannable.setSpan(span, 0, spannable.count(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

yourTextView.text = spannable

 

 - Result

 

 

 - Documents

https://developer.android.com/guide/topics/text/spans

 

스팬  |  Android 개발자  |  Android Developers

스팬은 강력한 마크업 객체로 문자나 단락 수준에서 텍스트 스타일을 지정하는 데 사용할 수 있습니다. 텍스트 객체에 스팬을 연결하여 다양한 방식으로 텍스트를 변경할 수 있습니다. 예를 들

developer.android.com

https://developer.android.com/reference/android/text/style/LeadingMarginSpan

 

LeadingMarginSpan  |  Android Developers

 

developer.android.com