Hanbit the Developer

[Kotlin] TextView의 더보기 기능 구현 본문

Mobile/Android

[Kotlin] TextView의 더보기 기능 구현

hanbikan 2021. 8. 8. 21:53

구현할 내용

 

 

구현

먼저 레이아웃은 아래와 같이 구성하였습니다.

<androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        >
        <TextView
            android:id="@+id/content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Hello World!"
            android:maxLines="5"
            android:ellipsize="end"
            android:textColor="@color/black"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            />
        <TextView
            android:id="@+id/view_more"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="더보기"
            android:visibility="gone"
            app:layout_constraintTop_toBottomOf="@id/content"
            app:layout_constraintStart_toStartOf="parent"
            />

 </androidx.constraintlayout.widget.ConstraintLayout>

1. 컨텐츠 텍스트와 "더보기" 텍스트가 세로로 붙어있는 구조입니다.

2. content에 maxLines, ellipsize를 설정하여, 글이 길어져서 maxLine를 넘어가면 글자 뒤에 "..."이 뜨게 하였습니다.

3. view_more는 더보기 텍스트이며 초기에는 보이지 않게 설정하였습니다.

 

다음은 context TextView에 적용할 코드입니다. 아래 함수를 onResume()에서 호출하였습니다.

private fun setViewMore(contentTextView: TextView, viewMoreTextView: TextView){
    // getEllipsisCount()을 통한 더보기 표시 및 구현
    contentTextView.post {
        val lineCount = contentTextView.layout.lineCount
        if (lineCount > 0) {
            if (contentTextView.layout.getEllipsisCount(lineCount - 1) > 0) {
                // 더보기 표시
                viewMoreTextView.visibility = View.VISIBLE

                // 더보기 클릭 이벤트
                viewMoreTextView.setOnClickListener {
                    contentTextView.maxLines = Int.MAX_VALUE
                    viewMoreTextView.visibility = View.GONE
                }
            }
        }
    }

 

1. 컨텐츠 텍스트가 maxLines를 넘어가서, 마지막 줄에 ellipsis(...)가 형성되었는지 체크합니다.

2. 더보기 텍스트를 보이게 합니다.(View.VISIBLE)

3. 더보기 텍스트 클릭 이벤트: 컨텐츠 텍스트의 maxLines를 무한대로 설정하여 텍스트가 가려지는 것 없이 모두 보여지게 합니다. 그리고 더보기 텍스트를 가립니다.(View.GONE)

4. 가장 바깥에 있는 contentTextView.post() 함수: contentTextView가 그려지기 전에는 lineCount, getEllipsisCount()를 제대로 알 수 없습니다. View.post() 메서드는 안드로이드에서 UI 작업을 뷰가 다음에 그려질 때까지 지연시키기 위해 사용됩니다. 이 메서드를 사용하면, 전달된 Runnable 객체가 UI 스레드(메인 스레드)의 메시지 큐에 포함되어, 현재 진행 중인 모든 레이아웃 계산, 측정, 그리기 작업이 완료된 후에 실행됩니다. 이를 통해 뷰와 관련된 변경 사항이 안전하게 처리되고, 뷰가 완전히 그려진 상태에서 코드를 실행할 수 있습니다.

 

완성!

 

관련 문서

https://developer.android.com/reference/android/text/Layout#getEllipsisCount(int)