各种viewAndroid知识Android技术知识

RecyclerView的item选中放大

2017-02-22  本文已影响1175人  风少侠

[TOC]

需求

最近在做的一个TV项目,我们知道TV一般是通过遥控器来进行选择的,因此有这样一个需求,需要在item被选中(获得焦点)时放大该item,电视不好录屏,效果图就不上了,大家应该都见过。

实现

首先假设我们的item是一个ImageButton(当然也可以是其他view),我们来自定义一个FoucseImageButton继承ImageButton,并重写onFocusChanged方法:

/**
 * 获得焦点时放大的ImageButton
 * Created by lxf on 2017/2/21.
 */
public class FocuseImageButton extends ImageButton {
    public FocuseImageButton(Context context) {
        super(context);
    }

    public FocuseImageButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FocuseImageButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
        super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
        if (gainFocus) {
            scaleUp();
        } else {
            scaleDown();
        }
    }

    //1.08表示放大倍数,可以随便改
    private void scaleUp() {
        ViewCompat.animate(this)
                .setDuration(200)
                .scaleX(1.08f)
                .scaleY(1.08f)
                .start();
    }

    private void scaleDown() {
        ViewCompat.animate(this)
                .setDuration(200)
                .scaleX(1f)
                .scaleY(1f)
                .start();
    }
}

代码很简单,就是获取焦点时放大item,失去焦点时缩小item。当然,如果你的item是LinearLayout等,别忘了设置focusable为true。
  看起来好像效果已经可以实现了,但是一运行发现并不是这么回事,你会发现第一行的item在放大时会被RecyclerView的边界遮挡住一部分,这时候只需要将RecyclerView的父布局的clipChildren设为false就好。

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="40dp"
        android:orientation="vertical"
        android:clipChildren="false"
        android:clipToPadding="false"
        tools:context="cn.izis.yzgotvnew.ui.fragment.ExerciseFragment">

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/sele_return"
            android:background="@null"
            android:layout_marginTop="20dp"
            android:layout_marginBottom="20dp"
            android:onClick="@{fragment.finish}"
            />

        <lxf.widget.recyclerview.LoadMoreRecyclerView
            android:id="@+id/recy_exer_title2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            />

    </LinearLayout>
上一篇 下一篇

猜你喜欢

热点阅读