Android 浮动按钮的伸缩效果
在做项目时想增加点动感,于是就有如下效果:
实现起来也很简单,通过属性动画和recyclerview 滑动结合就很好实现了。
通过给recycleview添加一个滑动监听:通过滚动的差值来处理动画
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { if (dy > 0 ){ hidenFabAnim(); }else{ showFabAnim(); } } });
两个动画如下:
/** * 动画隐藏浮动按钮 */ private void hidenFabAnim() { if (!isFabAnimg && mActionButton != null && mActionButton.getVisibility() == View.VISIBLE) { Animator animator = ObjectAnimator.ofFloat(mActionButton, "translationY", 0f, 100f); animator.setDuration(500); animator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { isFabAnimg = true; } @Override public void onAnimationEnd(Animator animation) { isFabAnimg = false; mActionButton.setVisibility(View.GONE); } @Override public void onAnimationCancel(Animator animation) { isFabAnimg = false; } @Override public void onAnimationRepeat(Animator animation) { } }); animator.start(); } } /** * 动画显示浮动按钮 */ private void showFabAnim(){ if (mActionButton != null && !isFabAnimg && mActionButton.getVisibility() == View.GONE) { Animator animator = ObjectAnimator.ofFloat(mActionButton,"translationY",100f,0f); animator.setDuration(500); animator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { isFabAnimg = true; } @Override public void onAnimationEnd(Animator animation) { isFabAnimg = false; } @Override public void onAnimationCancel(Animator animation) { isFabAnimg = false; } @Override public void onAnimationRepeat(Animator animation) { } }); mActionButton.setVisibility(View.VISIBLE); animator.start(); } }
动画中给定了移出屏幕和显示在屏幕的距离是100,这个值并不是那么确定性,项目中需要通过屏幕密度来算这个值的大小,以便适应更好的滑动效果;定义了个
isFabAnimg 变量,用来明确动画的状态,避免了重复执行显示或者隐藏的动画。
可见android中要实现某些小效果还是非常的方便的