[Android]TextViewのマーキー(marquee)をRecyclerView等でも動かさせる

そもそもマーキーって?

TextViewのandroid:ellipsizemarqueeに設定するとViewの幅より長いテキストの場合、水平方向にスクロールしてくれるやつ。

Android標準の機能だから簡単に水平方向にスクロールしてくれると思っていたのよ。

確かに動いた。

TextViewが1つしか配置していないlayoutファイルなら・・・。

ググってみると、、、

TextView マーキー動かない

TextView マーキー自動スクロールしない

TextView マーキー動作しない

動かない人たくさんw

ある人は、

ViewGroupTextView挟むと動くようになるよ!

って書いてあったり

ある人は、

HorizontalScrollViewTextViewを入れてScrollViewを自動スクロールさせるよ!

って書いてあったり、、、。

ViewGroupの方を試してみたけど、うまく動かなかった・・・。

ってことでうまく行った方法を晒してみる。

スポンサーリンク

実装

カスタムTextViewを作成する

class AutoScrollingTextView : TextView {
    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttrs: Int) : super(context, attrs, defStyleAttrs)

    override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) {

        if (focused) {
            super.onFocusChanged(focused, direction, previouslyFocusedRect)
        }
    }

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

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

常にフォーカス当てて、フォーカス外してあげないよ作戦。

xmlファイル

//
<hoge.package.view.AutoScrollingTextView
    android:layout_width="100dp"
    android:layout_height="match_parent"
    android:ellipsize="marquee"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:marqueeRepeatLimit="marquee_forever"
    android:singleLine="true"
    android:textSize="16dp"
    android:text="長い文章" />

一般的?なマーキーの設定をすればOK。

これで自動で動いてくれるようにある。なった!

タイトルとURLをコピーしました