AndroidTV 获取焦点View放大效果实现方式
需求
电视开发最常见的就是view获焦后要有放大效果,让用户明显看到。这里总结两个实现方法,以后遇到其他的再补充。
方式一:ViewCompat.animate(view)
1、注册焦点变化监听
mBtnFocus1.setOnFocusChangeListener(this);
2、有焦点变化的时候进行放缩
@Override
public void onFocusChange(View view, boolean hasFocus) {switch (view.getId()) {case R.id.btn_focus1:if (hasFocus) {//获焦后放大1.2倍ViewCompat.animate(view).scaleX(1.2f).scaleY(1.2f).translationZ(1.2f).start();} else {//丢失焦点后缩回正常ViewCompat.animate(view).scaleX(1.0f).scaleY(1.0f).translationZ(1.0f).start();}}
}
方式二:StateListAnimator
1、res文件夹下新建animator文件夹,然后新建focus_scale_anim.xml文件。
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"><item android:state_focused="true"><set><objectAnimatorandroid:duration="@android:integer/config_shortAnimTime"android:propertyName="scaleX"android:valueTo="1.2"android:valueType="floatType" /><objectAnimatorandroid:duration="@android:integer/config_shortAnimTime"android:propertyName="scaleY"android:valueTo="1.2"android:valueType="floatType" /></set></item><item android:state_focused="false"><set><objectAnimatorandroid:duration="@android:integer/config_shortAnimTime"android:propertyName="scaleX"android:valueTo="1"android:valueType="floatType" /><objectAnimatorandroid:duration="@android:integer/config_shortAnimTime"android:propertyName="scaleY"android:valueTo="1"android:valueType="floatType" /></set></item>
</selector>
2、然后在xml布局文件中,把需要放缩的view加上该动画
<Buttonandroid:id="@+id/btn_focus3"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="50px"android:stateListAnimator="@animator/focus_scale_anim"android:text="focus3" />
3、或者在代码中实现也可以
StateListAnimator animator = AnimatorInflater.loadStateListAnimator(this, R.animator.focus_scale_anim);
mBtnFocus2.setStateListAnimator(animator);
上面分别用focus3和focus2分别用了xml和代码的方式,运行效果一致。
参考文章:
StateListAnimator的应用