[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>