프로그래밍 방식으로 작성한 TextView에 스크롤바가 보이는 스크롤 기능 적용하기

hongbeom
Jan 6, 2021

--

xml로 작성한 방식이 아닌 프로그래밍 방식으로 생성한 TextView에 스크롤을 적용해봅니다.

Scrollable TextView

TextView스크롤바가 보이는 스크롤 기능을 적용할 때 보통 우리는 xml 코드 상에서 scrollable 옵션을 적용하여 movementMethod를 사용하거나 TextViewScrollView로 감싸서 사용합니다. 이 때 scollbars 옵션을 지정해주지 않는다면 스크롤바가 보이지 않습니다.

// use scrollbars in xml<TextView
android:id="+@id/textView_my"
...
android:scrollbars="vertical"/>
// in code...val textView = findViewById<TextView>(R.id.textView_my)
textView.movementMethod = ScrollingMovementMethod.getInstance()
// and use ScrollView<ScrollView>
<TextView/>
</ScrollView>

하지만 layout.xml 파일 없이 오직 프로그래밍 방식으로 구현해야한다면 어떻게 해야할 까요?

사실 방법은 간단합니다.

Style.xml

먼저 style.xml 파일에 커스텀 스타일을 적용합니다.

<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="VerticalScrollableTextView">
<item name="android:scrollbars">vertical</item>
</style>
</resources>

ContextThemeWrapper

그리고 ContextThemeWrapper를 사용하여 TextView를 생성하면 끝입니다.

val textView = TextView(
ContextThemeWrapper(context, R.style.VerticalScrollableTextView
)
textView.movementMethod = ScrollingMovementMethod.getInstance()

동적으로 TextView를 구현할 경우 스크롤바가 보이는 scrollable한 TextView를 만들기가 까다로운데 ContextThemeWrapperstyle을 사용하면 간단하게 만들 수 있습니다.

이상 미세먼지 팁이었습니다.

읽어주셔서 감사합니다!

--

--

hongbeom
hongbeom

No responses yet