Android如何为设置Preference添加闪烁动画吸引用户注意
Android Preference跳转定位项高亮闪烁实现(对齐原生设置效果)
原生系统设置的高亮效果没有提供Preference组件的公开API,内部实现逻辑就是对Preference绑定的列表项View添加前景蒙层做透明度渐变动画,以下方案可1:1还原原生效果,兼容所有官方Preference组件及自定义Preference。
核心实现步骤
1. 获取定位到的目标Preference对应的ItemView
Preference页面内部本质是用RecyclerView渲染所有列表项,你已经实现了滚动定位,只需要等滚动停止、布局完成后,通过适配器位置拿到对应项的View即可,不要尝试直接从Preference类本身找拿View的API,没有公开暴露的方法。
// 等RecyclerView滚动停止、布局完成后执行,避免返回null preferenceRecyclerView.post { val targetViewHolder = preferenceRecyclerView.findViewHolderForAdapterPosition(targetScrollPosition) val targetItemView = targetViewHolder?.itemView ?: return@post // 后续动画逻辑在这里执行 }
2. 添加闪烁动画逻辑
原生效果是用主题强调色的半透明蒙层做3次渐显渐隐循环,单次渐入渐出时长400ms,动画结束后自动清理蒙层不影响原有交互:
// 取当前主题的强调色作为高亮色,也可自定义颜色 val highlightColor = ContextCompat.getColor(targetItemView.context, R.color.design_default_color_primary) val highlightDrawable = ColorDrawable(highlightColor).apply { alpha = 0 } // 适配不同版本设置蒙层:高版本用foreground,低版本用ViewOverlay不侵入原有布局 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { targetItemView.foreground = highlightDrawable } else { targetItemView.overlay.add(highlightDrawable) highlightDrawable.setBounds(0, 0, targetItemView.width, targetItemView.height) } // 执行闪烁动画 ValueAnimator.ofInt(0, 153, 0).apply { duration = 1200 // 400ms一个闪烁周期,共3次 repeatCount = 0 addUpdateListener { anim -> val currentAlpha = anim.animatedValue as Int highlightDrawable.alpha = currentAlpha // 低版本需手动更新蒙层尺寸,避免布局变化导致错位 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { highlightDrawable.setBounds(0, 0, targetItemView.width, targetItemView.height) } } doOnEnd { // 动画结束清理蒙层,不影响原有点击、按压态 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { targetItemView.foreground = null } else { targetItemView.overlay.remove(highlightDrawable) } } start() }
避坑说明
- 不要直接修改Preference对应布局内控件的background,会破坏原生的按压涟漪、选中态等交互样式,用前景/ViewOverlay的方案侵入性为0
- 如果是页面首次打开就触发定位+动画,不要直接在
onCreate/onViewCreated里取View,必须等RecyclerView完成首次布局后再执行,post到消息队列或者加OnPreDrawListener都可以 - 该方案不依赖特定Preference版本,从AndroidX Preference到原生framework的Preference都可用,只要内部是用RecyclerView渲染列表即可
内容的提问来源于stack exchange,提问作者Arun kumar
相关产品推荐
相关产品推荐

