본문 바로가기

Android/UI

[안드로이드] 텍스트 추가시 스크롤 자동 내리기

728x90
반응형

 

스크롤 뷰 안에 있는 텍스트뷰에 텍스트를 추가하고,

추가된 텍스트뷰가 보이도록 스크롤 뷰가 자동으로 내려가야 합니다.

여러가지 방법이 있지만, 가장 잘 동작하는 코드입니다.

 

PerfectScrollableTextView Class를 만듭니다.

import android.content.Context
import android.graphics.Rect
import android.util.AttributeSet
import android.widget.TextView


class PerfectScrollableTextView : TextView {
    constructor(context: Context?, attrs: AttributeSet?, defStyle: Int) : super(
        context,
        attrs,
        defStyle
    ) {
        isVerticalScrollBarEnabled = true
        setHorizontallyScrolling(false)
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        isVerticalScrollBarEnabled = true
        setHorizontallyScrolling(false)
    }

    constructor(context: Context?) : super(context) {
        isVerticalScrollBarEnabled = true
        setHorizontallyScrolling(false)
    }

    override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
        if (focused) super.onFocusChanged(focused, direction, previouslyFocusedRect)
    }

    override fun onWindowFocusChanged(focused: Boolean) {
        if (focused) super.onWindowFocusChanged(focused)
    }

    override fun isFocused(): Boolean {
        return true
    }
}

 

 

그다음 layout의 ScrollView안에 있는 TextViewcom.your.package.PerfectScrollableTextView로 바꾸어줍니다.

        <ScrollView
            android:scrollbars="vertical"
            android:id="@+id/scroller"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="40dp"
            android:fillViewport="true">

            <com.lillyddang.simpleble.util.PerfectScrollableTextView
                android:id="@+id/txt_read"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="10dp"
                android:lineSpacingExtra="7dp"
                android:textColor="@color/black" />
        </ScrollView>

 

텍스트 추가시, ScrollToBottom 메서드를 실행합니다. layout id는 data binding을 사용하였습니다.

binding.txtRead.append(read)

if ((binding.txtRead.measuredHeight - binding.scroller.scrollY) <=
     (binding.scroller.height + binding.txtRead.lineHeight)) {
          scrollToBottom()
}

..

private fun scrollToBottom() {
    binding.scroller.post {
         binding.scroller.smoothScrollTo(0, binding.txtRead.bottom)
    }
}

 

728x90
반응형