package com.beanpodtech.allinone.widget;

import android.content.Context;
import android.graphics.Rect;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.TextView;

import androidx.annotation.Nullable;

public class MarqueeTextView extends TextView {
    public MarqueeTextView(Context context) {
        this(context, null);
    }

    public MarqueeTextView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MarqueeTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        //默认循环一次
        setRepeatCount(1);
    }

    /**
     * 强制获取焦点
     *
     * @return
     */
    @Override
    public boolean isFocused() {
        return true;
    }


    /**
     * 用于EditText抢注焦点的问题
     */
    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        if (focused) {
            super.onFocusChanged(focused, direction, previouslyFocusedRect);
        }
    }

    /**
     * Window与Window间焦点发生改变时的回调
     * 解决Dialog抢了焦点后跑马灯停止
     */
    @Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
        if (hasWindowFocus) {
            super.onWindowFocusChanged(hasWindowFocus);
        }
    }

    /**
     * 设置跑马灯循环次数，其中-1表示无限循环
     *
     * @param limit
     */
    public void setRepeatCount(int limit) {
        //设置单行
        setSingleLine();
        //设置Ellipsize
        setEllipsize(TextUtils.TruncateAt.MARQUEE);
        //获取焦点
        setFocusable(true);
        //走马灯的重复次数,-1表示无限循环
        setMarqueeRepeatLimit(limit);
        //强制获得焦点
        setFocusableInTouchMode(true);
    }
}
