Android

Android 自定義跑馬燈 MarqueeTextView

1.自定義View

import android.content.Context
import android.graphics.Rect
import android.text.TextUtils
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView

class MarqueeTextView(context: Context, attrs: AttributeSet) : AppCompatTextView(context, attrs) {
    init {
        //設定單行
        setSingleLine()
        //設定跑馬燈
        ellipsize = TextUtils.TruncateAt.MARQUEE
        //獲取焦點
        isFocusable = true
        //-1代表無限
        marqueeRepeatLimit = -1
        //強制獲取焦點
        isFocusableInTouchMode = true
    }

    //永遠為焦點
    override fun isFocused(): Boolean {
        return true
    }

    //解決EditText搶焦點
    override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
        if (focused) {
            super.onFocusChanged(true, direction, previouslyFocusedRect)
        }
    }

    //Window與Window間焦點發生改變
    override fun onWindowFocusChanged(hasWindowFocus: Boolean) {
        if (hasWindowFocus) {
            super.onWindowFocusChanged(true)
        }
    }
}

2.在XML調用

    <com.fly.githubtestkotlin.MarqueeTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="#ff0000"
        android:textSize="36sp"
        android:text="我是跑馬燈 你也是跑馬燈 大家都是跑馬燈"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

3.效果展示

發表迴響