본문 바로가기
안드로이드 코틀린

[Kotlin][Android] 텍스트뷰 생략 옵션 동적으로 변경하기

by teamnova 2022. 2. 15.

안녕하세요 이번 포스트에서는 텍스트뷰의 ellipsis 속성 값을 동적으로 변경해보겠습니다.

 

텍스트뷰와 여러개의 버튼이 있는 레이아웃을 만듭니다.

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:ellipsize="middle"
        android:maxLines="1"
        android:text="동해물과 백두산이 마르고 닳도록 하느님이 보우하사 우리나라 만세 무궁화 삼천리 화려 강산 대한 사람 대한으로 길이 보전하세" />

    <Button
        android:id="@+id/btn_start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="start" />

    <Button
        android:id="@+id/btn_middle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="middle" />

    <Button
        android:id="@+id/btn_end"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="end" />

    <Button
        android:id="@+id/btn_marquee"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="marquee" />
</androidx.appcompat.widget.LinearLayoutCompat>

 

각 버튼을 눌렀을 때마다 텍스트뷰의 생략 옵션을 변경해주는 코드를 액티비티에 넣어줍니다.

    val textView: TextView by lazy { findViewById(R.id.tv) }
    val btnStart: Button by lazy { findViewById(R.id.btn_start) }
    val btnMiddle: Button by lazy { findViewById(R.id.btn_middle) }
    val btnEnd: Button by lazy { findViewById(R.id.btn_end) }
    val btnMarquee: Button by lazy { findViewById(R.id.btn_marquee) }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        btnStart.setOnClickListener { textView.ellipsize = TextUtils.TruncateAt.START }
        btnMiddle.setOnClickListener { textView.ellipsize = TextUtils.TruncateAt.MIDDLE }
        btnEnd.setOnClickListener { textView.ellipsize = TextUtils.TruncateAt.END }
        btnMarquee.setOnClickListener { textView.ellipsize = TextUtils.TruncateAt.MARQUEE }
    }