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的应用

相关推荐
刘志辉15 分钟前
vue传参方法
android·vue.js·flutter
前期后期3 小时前
Android OkHttp源码分析(一):为什么OkHttp的请求速度很快?为什么可以高扩展?为什么可以高并发
android·okhttp
轻口味5 小时前
Android应用性能优化
android
全职计算机毕业设计5 小时前
基于 UniApp 平台的学生闲置物品售卖小程序设计与实现
android·uni-app
dgiij6 小时前
AutoX.js向后端传输二进制数据
android·javascript·websocket·node.js·自动化
SevenUUp7 小时前
Android Manifest权限清单
android
高林雨露7 小时前
Android 检测图片抓拍, 聚焦图片后自动完成拍照,未对准图片的提示请将摄像头对准要拍照的图片
android·拍照抓拍
wilanzai7 小时前
Android View 的绘制流程
android
INSBUG8 小时前
CVE-2024-21096:MySQLDump提权漏洞分析
android·adb
Mercury Random10 小时前
Qwen 个人笔记
android·笔记