TV焦点框控件

/**

  • 功能简介:获取焦点时放大
    */
public class TVMetroRelativeLayout extends RelativeLayout {
    /**
     * 无效果
     */
    public final static int ANIM_DEFAULT = 0;
    
    /**
     * 平移
     */
    public final static int ANIM_TRASLATE = 1;
    
    /**
     * 光标tag
     */
    private final String cursorTag = "cursor_rcs";
    
    /**
     * 光标
     */
    private View cursor;
    
    /**
     * 光标资源
     */
    private int cursorRes; 
    
    /**
     * 光标飘移动画 默认无效果
     */
    private int animationType;
    
    /**
     * 放大用时
     */
    private int durationLarge;
    /**
     * 缩小用时
     */
    private int durationSmall ;
    /**
     * 滑动用时
     */
    private int durationTranslate=1000;
     
    /**
     * 放大高度
     */
    private int biggerHeight = 40;
    
    /**
     * 放大宽度
     */
    private int biggerWidth = 40;
    
    /**
     * 阴影宽高
     */
    private int shadow = 5; 
    
    /**
     * 光标高度
     */
    private int cursorHeight = 0;
    /**
     * 光标宽度
     */
    private int cursorWidth = 0;
    
    /**
     * 鼠标二次点击
     */
    private boolean clickSecond = true;
    
    private AnimatorSet animatorSet;
    
    private ObjectAnimator largeX;

    private OnChildSelectListener onChildSelectListener;
    
    private OnChildClickListener onChildClickListener;

    private View focusView = null;
    
    public void setBiggerHeight(int biggerHeight){
        this.biggerHeight = biggerHeight;
    }
    
    public void setBiggerWidth(int biggerWidth){
        this.biggerWidth = biggerWidth;
    }
    
    public void setShadow(int shadow){
        this.shadow = shadow;
    }
    
    public int getCursorRes() {
        return cursorRes;
    }

    public void setCursorRes(int cursorRes) {
        this.cursorRes = cursorRes;
    } 

    public TVMetroRelativeLayout(Context context) {
        this(context, null);
    }

    public TVMetroRelativeLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public TVMetroRelativeLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        float def=(float)getResources().getDimension(R.dimen.y14);
        TypedArray custom = getContext().obtainStyledAttributes(attrs, R.styleable.TVMetroRelativeLayout);
        this.cursorRes = custom.getResourceId(R.styleable.TVMetroRelativeLayout_cursorRes, 0);
        this.animationType = custom.getInt(R.styleable.TVMetroRelativeLayout_animationType, 0);
        this.durationLarge = custom.getInteger(R.styleable.TVMetroRelativeLayout_durationLarge, /*6*/300);
        this.durationSmall = custom.getInteger(R.styleable.TVMetroRelativeLayout_durationSmall, /*6*/300);
        this.durationTranslate = custom.getInteger(R.styleable.TVMetroRelativeLayout_durationTranslate, 6);
        this.biggerHeight = (int) custom.getDimension(R.styleable.TVMetroRelativeLayout_biggerHeight, 2);
        this.biggerWidth = (int) custom.getDimension(R.styleable.TVMetroRelativeLayout_biggerWidth, 2);
        this.shadow = (int) custom.getDimension(R.styleable.TVMetroRelativeLayout_shadow, def);
        this.clickSecond = custom.getBoolean(R.styleable.TVMetroRelativeLayout_clickSecond, true);
        custom.recycle();
        // 关闭子控件动画缓存 使嵌套动画更流畅
        setAnimationCacheEnabled(false);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (changed) {
            super.onLayout(changed, l, t, r, b);
        } else {
            int cCount = getChildCount();
            int cWidth = 0;
            int cHeight = 0;
            /**
             * 遍历所有childView根据其宽和高,以及margin进行布局 选中框无需重定位??初始位置
             */
            for (int i = 0; i < cCount; i++) {
                View childView = getChildAt(i);

                if (childView.getTag() != null && childView.getTag().toString().equals(cursorTag)) {
                    continue;
                }

                cWidth = childView.getMeasuredWidth();
                cHeight = childView.getMeasuredHeight();

                int cl = 0, ct = 0, cr = 0, cb = 0;

                cl = childView.getLeft();
                ct = childView.getTop();
                cr = cl + cWidth;
                cb = cHeight + ct;
                childView.layout(cl, ct, cr, cb);
            }
        }

    }
    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        bindEvent();
    }

    // 初始化焦点
    private void bindEvent() {
        bindOnChildFocusEvent();
        
        // 初始化焦点
        final View focus = findFocus();
        if (focus != null) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    focus.requestFocus();
                    moveCover(focus);
                }
            }, 300);
        }
    }

    /**
     * 光标移动 到达后 与控件同时放大
     */
    private void moveCover(View item) {
        if (cursor == null) {
            cursor = new View(getContext());
            cursor.setFocusable(false);
            cursor.setTag(cursorTag);
            cursor.setBackgroundResource(cursorRes);
            //给一个初始大小
            LayoutParams params = new LayoutParams(50, 50);
            cursor.setLayoutParams(params);
            this.addView(cursor);
        }
        setBorderParams(item);
    }

/**
     * 还原控件状态
     */

    private void returnCover(View item) {
        if (cursor == null) {
            return;
        }
        cursor.setVisibility(View.INVISIBLE);
        cursor.clearAnimation();//光标渐变动画停止
        scaleToNormal(item);
    }

    private void scaleToLarge(View item) {
        if (!item.isFocused()) {
            return;
        }
        if (onChildSelectListener != null) {
            onChildSelectListener.onChildSelect(null);
        }
        animatorSet = new AnimatorSet();
        largeX = ObjectAnimator.ofFloat(item, "ScaleX", 1f, biggerWidth * 1.0f / item.getMeasuredWidth() + 1);
        ObjectAnimator largeY = ObjectAnimator.ofFloat(item, "ScaleY", 1f, biggerHeight * 1.0f / item.getMeasuredHeight() + 1);
        
        //放大效果不从1开始的原因是:和放大的组件进行同步
        ObjectAnimator cursorX = ObjectAnimator.ofFloat(cursor, "ScaleX", (cursorWidth + shadow) * 1.0f / cursorWidth, (cursorWidth + biggerWidth + shadow) * 1.0f / cursorWidth);
        ObjectAnimator cursorY = ObjectAnimator.ofFloat(cursor, "ScaleY", (cursorHeight + shadow) * 1.0f / cursorHeight, (cursorHeight + biggerHeight + shadow) * 1.0f / cursorHeight);

        animatorSet.setDuration(durationLarge);
        animatorSet.play(largeX).with(largeY).with(cursorX).with(cursorY);
        animatorSet.start();
    }

    private void scaleToNormal(View item) {
        if (animatorSet == null) {
            return;
        }
        if (animatorSet.isRunning()) {
            animatorSet.cancel();
        }
        ObjectAnimator oa = ObjectAnimator.ofFloat(item, "ScaleX", 1f);
        oa.setDuration(durationSmall);
        oa.start();
        ObjectAnimator oa2 = ObjectAnimator.ofFloat(item, "ScaleY", 1f);
        oa2.setDuration(durationSmall);
        oa2.start();
    } 

    /**
     * 指定光标相对位置
     */
    private void setBorderParams(View item) {
        cursor.clearAnimation();
        cursor.setVisibility(View.VISIBLE);

        // 判断类型
        LayoutParams params = (LayoutParams) item.getLayoutParams();
        final int l = item.getLeft();
        final int t = item.getTop();
        final int r = item.getLeft() + params.width;
        final int b = item.getTop() + params.height;
        cursorWidth = r - l;
        cursorHeight = b - t;

        switch (animationType) {
            case ANIM_DEFAULT:
                cursor.layout(l, t, r, b);
                item.bringToFront();
                cursor.bringToFront();
                //光标做渐变 动画
                Animation anim = new AlphaAnimation(1.0f, 0f);
                anim.setDuration(250);
                anim.setRepeatCount(Animation.INFINITE);
                anim.setRepeatMode(Animation.REVERSE);
//              cursor.startAnimation(anim);
                scaleToLarge(item);
                break;

            case ANIM_TRASLATE:
                if (cursor.getLeft() <= 0) {
                    cursor.layout(l, t, r, b);
                }
                item.bringToFront();
                cursor.bringToFront();
    
                TvAnimator animator = new TvAnimator(cursor, item);
                animator.setTargetParams(l, t, r - l, b - t);
                animator.execute();
                break;
        }

    }

    class TvAnimator extends AsyncTask<Void, Integer, Integer> {
        private View target, item;
        private int l, t, cl, ct;
        private int width, cwidth, height, cheight;
        private int dX, dY, dW, dH;
        private int frequence = 17;  
        private int cbiggerWidth;
        private int cbiggerHeight;
        private int animDuration = 6;
        
        TvAnimator(View target, View item) {
            this.target = target;
            this.item = item;
        }

        public void setTargetParams(int l, int t, int width, int height) {
            this.l = l;
            this.t = t;
            this.width = width;
            this.height = height;
            this.cl = target.getLeft();
            this.ct = target.getTop();
            this.cwidth = target.getWidth();
            this.cheight = target.getHeight(); 
            this.cbiggerWidth = shadow + biggerWidth;
            this.cbiggerHeight = shadow + biggerHeight;
        } 

        @Override
        protected void onPreExecute() {
            dW = (int) (width - cwidth > 0 ? Math.ceil((width - cwidth)
                    / (frequence * 1.0)) : Math.floor((width - cwidth)
                    / (frequence * 1.0)));
            dH = (int) (height - cheight > 0 ? Math.ceil((height - cheight)
                    / (frequence * 1.0)) : Math.floor((height - cheight)
                    / (frequence * 1.0)));
            dX = (int) (l - cl > 0 ? Math.ceil((l - cl) / (frequence * 1.0))
                    : Math.floor((l - cl) / (frequence * 1.0)));
            dY = (int) (t - ct >= 0 ? Math.ceil((t - ct) / (frequence * 1.0))
                    : Math.floor((t - ct) / (frequence * 1.0)));
        }

        @Override
        protected Integer doInBackground(Void... params) {

            while (cl != l || t != ct || cwidth != width || cheight != height) {

                if (Math.abs(cl - l) <= Math.abs(dX)) {
                    cl = l;
                } else {
                    cl += dX;
                }

                if (Math.abs(ct - t) <= Math.abs(dY)) {
                    ct = t;
                } else {
                    ct += dY;
                }

                if (Math.abs(width - cwidth) <= Math.abs(dW)) {
                    cwidth = width;
                    dW = 0;
                } else {
                    cwidth += dW;
                }

                if (Math.abs(height - cheight) <= Math.abs(dH)) {
                    cheight = height;
                    dH = 0;
                } else {
                    cheight += dH;
                }
                publishProgress(cl, ct, cl + cwidth + dW, ct + cheight + dH);
                try {
                    Thread.sleep(durationTranslate);
                } catch (InterruptedException e) {
                }
            }

            return null;
        }
        @Override
        protected void onPostExecute(Integer integer) {
            if (!item.isFocused()) {
                return;
            }
            animatorSet = new AnimatorSet();
            ValueAnimator largeX = ObjectAnimator.ofFloat(item, "ScaleX", 1f, biggerWidth * 1.0f / width + 1);
            ValueAnimator largeY = ObjectAnimator.ofFloat(item, "ScaleY", 1f, biggerHeight * 1.0f / height + 1);

            animatorSet.setDuration(durationLarge);
            animatorSet.setInterpolator(new DecelerateInterpolator(3.0f));
            animatorSet.play(largeX).with(largeY);
            animatorSet.start();
            // 中心放大 左上减 右下加 
            ValueAnimator animation = ValueAnimator.ofFloat(1f, animDuration);
            animation.setDuration(durationLarge);
            animation.setInterpolator(new DecelerateInterpolator(3.0f));
            animation.addUpdateListener(new AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float curScale = (Float) animation.getAnimatedValue();
                    int dw = (int) (cbiggerWidth * curScale / (animDuration * 2 ));
                    int dh = (int) (cbiggerHeight * curScale / (animDuration * 2 ));
                    target.layout(l - dw, t - dh, l + cwidth + dw, t + cheight + dh);
                }
            });
            animation.start(); 
        }
        @Override
        protected void onProgressUpdate(Integer... values) {
            target.layout(values[0], values[1], values[2], values[3]);
        }
    }

    private void bindOnChildClickEvent(){
        if (getChildCount() < 1) {
            return;
        }
        View child = null;
        for (int i = 0; i < getChildCount(); i++) {
            child = getChildAt(i);
            if (child != null) {
                if (onChildClickListener != null) {
                    child.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View child) {
                            if(clickSecond){    //鼠标二次点击才能正在激发控件的点击事件
                                if(child == focusView){
                                    onChildClickListener.onChildClick(child);
                                }else{ 
                                    child.setFocusable(true);
                                    child.setFocusableInTouchMode(true);
                                    child.requestFocus();
                                    child.requestFocusFromTouch();
                                }
                            }else{
                                onChildClickListener.onChildClick(child);
                            }
                        }
                    });
                }
            }
        }

    }

    private void bindOnChildSelectEvent(){
        if (getChildCount() < 1) {
            return;
        }
        View child = null;
        for (int i = 0; i < getChildCount(); i++) {
            child = getChildAt(i);
            if (child != null) {
                child.setOnFocusChangeListener(new OnFocusChangeListener() {
                    @Override
                    public void onFocusChange(final View child, boolean focus) {
                        if (focus) {
                            focusView = child;
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    moveCover(child);
                                }
                            }, 0);
                            // 选中事件
                            if (onChildSelectListener != null) {
                                onChildSelectListener.onChildSelect(child);
                            }
                        } else {
                            returnCover(child);
                        }
                    }
                });
            }
        }
    } 
    private void bindOnChildFocusEvent(){
        if (getChildCount() < 1) {
            return;
        }
        View child = null;
        for (int i = 0; i < getChildCount(); i++) {
            child = getChildAt(i);
            if (child != null) {
                child.setOnFocusChangeListener(new OnFocusChangeListener() {
                    @Override
                    public void onFocusChange(final View child, boolean focus) {
                        if (focus) {
                            focusView = child;
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    moveCover(child);
                                }
                            }, 0);
                        } else {
                            returnCover(child);
                        }
                    }
                });
            }
        }
    }
    public void setOnChildSelectListener(OnChildSelectListener onChildSelectListener) {
        this.onChildSelectListener = onChildSelectListener;
        bindOnChildSelectEvent();
    }

    public void setOnChildClickListener(OnChildClickListener onChildClickListener) {
        this.onChildClickListener = onChildClickListener;
        bindOnChildClickEvent();
    }

    public interface OnChildSelectListener {
        public void onChildSelect(View child);
    }

    public interface OnChildClickListener {
        public void onChildClick(View child);
    }

}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,547评论 6 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,399评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,428评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,599评论 1 274
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,612评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,577评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,941评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,603评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,852评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,605评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,693评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,375评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,955评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,936评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,172评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,970评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,414评论 2 342

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,401评论 25 707
  • 提起朱安或许没有几个人能知道这个连名字都普通不过的人。可是如果说她是鲁迅的原配夫人,部分人也会讶异,印象中鲁迅的妻...
    一片轻心阅读 2,437评论 12 16
  • 什么叫中观?就是套路。如果你为既定资源,既定需求的系统服务,套路足以胜任。因为一件事做到什么程度,多一点少一点的刻...
    夜澜听影阅读 1,737评论 0 0
  • 我们经常在centos的terminal下工作那么如何查看日历呢? 如何在terminal下查看日历? 语句:ca...
    ppmoon阅读 1,433评论 1 49
  • 欢愉之后尽是孤独 aloneness after entertainment 今年的正月十五是最特别的一个十五 T...
    Tiffany_的早餐阅读 205评论 0 1