AndroidTV 获取焦点View放大效果实现方式

需求

电视开发最常见的就是view获焦后要有放大效果,让用户明显看到。这里总结两个实现方法,以后遇到其他的再补充。

方式一:ViewCompat.animate(view)

1、注册焦点变化监听

java 复制代码
mBtnFocus1.setOnFocusChangeListener(this);

2、有焦点变化的时候进行放缩

java 复制代码
@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文件。

java 复制代码
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
	<item android:state_focused="true">
		<set>
			<objectAnimator
                android:duration="@android:integer/config_shortAnimTime"
                android:propertyName="scaleX"
                android:valueTo="1.2"
                android:valueType="floatType" />
           <objectAnimator
                android:duration="@android:integer/config_shortAnimTime"
                android:propertyName="scaleY"
                android:valueTo="1.2"
                android:valueType="floatType" />
        </set>
    </item>
    <item android:state_focused="false">
		<set>
			<objectAnimator
                android:duration="@android:integer/config_shortAnimTime"
                android:propertyName="scaleX"
                android:valueTo="1"
                android:valueType="floatType" />
           <objectAnimator
                android:duration="@android:integer/config_shortAnimTime"
                android:propertyName="scaleY"
                android:valueTo="1"
                android:valueType="floatType" />
        </set>
    </item>
</selector>

2、然后在xml布局文件中,把需要放缩的view加上该动画

java 复制代码
<Button
    android: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、或者在代码中实现也可以

java 复制代码
StateListAnimator animator = AnimatorInflater.loadStateListAnimator(this, R.animator.focus_scale_anim);
mBtnFocus2.setStateListAnimator(animator);

上面分别用focus3和focus2分别用了xml和代码的方式,运行效果一致。

参考文章:

StateListAnimator的应用

相关推荐
_一条咸鱼_1 小时前
揭秘 Android TextInputLayout:从源码深度剖析其使用原理
android·java·面试
_一条咸鱼_1 小时前
揭秘!Android VideoView 使用原理大起底
android·java·面试
_一条咸鱼_1 小时前
深度揭秘!Android TextView 使用原理全解析
android·java·面试
_一条咸鱼_1 小时前
深度剖析:Android Canvas 使用原理全揭秘
android·java·面试
_一条咸鱼_1 小时前
深度剖析!Android TextureView 使用原理全揭秘
android·java·面试
_一条咸鱼_1 小时前
揭秘!Android CheckBox 使用原理全解析
android·java·面试
_一条咸鱼_1 小时前
深度揭秘:Android Toolbar 使用原理的源码级剖析
android·java·面试
_一条咸鱼_1 小时前
揭秘 Java ArrayList:从源码深度剖析其使用原理
android·java·面试