Android 浮动操作按钮动画

Android Floating Action Button animation

当滚动视图移动时,我想要的只是一个简单的动画。我已经尝试了一些解决方案,但是 none 有效 perfectly/smoothly。如果我滚动,我想隐藏带有向下滑动动画的 fab,如果 2 秒后没有任何反应,则 fab 显示带有向上滑动动画。我知道这是一个基本问题,感谢您的耐心等待。

提前致谢。

final ScrollView scroll = (ScrollView) v.findViewById(R.id.sw);
scroll.setOnTouchListener(new View.OnTouchListener()){
   @Override
   public boolean onTouch(View v, Motionevent event){
      int action = event.getAction();
      if (action == Motionevent.ACTION_MOVE){

      //slide down animation here

      }else{
        new Handler().postDelayed(new Runnable(){
          public void run(){

          //slide up animation here

          }
        }, 2000);
      }
    return false;
  }
});

这里是a tutorial,如何使用带有滚动动画的 FAB 按钮。

基本上:

  1. 使用 v22.2.1 支持 v4 库,有一个 show()hide() 方法执行浮动操作按钮的 fade-in 和 fade-out 动画
  2. 您必须将 ScrollView 和 FAB 放在 CoordinatorLayout 中。
  3. 将 FAB layout_anchor 设置为 ScrollView's id
  4. 创建一个class并扩展FloatingActionButton.Behavior class并在布局xml
  5. 中将其设置为FAB的layout_behavior属性
  6. 覆盖您的行为class onStartNestedScroll 以检查是否垂直
  7. 覆盖您的行为 class onStopNestedScroll 以在向下滚动时调用 child 的(FAB)参数 hide() 方法和 postDelay Runnable 以显示2秒后FAB

布局如:

<android.support.design.widget.CoordinatorLayout
... >
    <ScrollView
    android:id="@+id/myList"
    ...
    />
        <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        app:layout_anchor="@id/myList"
        app:layout_behavior="package.CustomScrollAwareBehavior"
        ...
        />
    </android.support.design.widget.CoordinatorLayout>

我建议,还要在行为 class 中创建一个 Handler 来调用 FAB 的 show() 方法。 行为 class 喜欢(未测试):

public class CustomScrollAwareBehavior extends FloatingActionButton.Behavior{

private Handler handler = new Handler();
private FloatingActionButton fab;

public CustomScrollAwareBehavior(Context context, AttributeSet attrs) {
    super();
}

@Override
public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout,
                                   FloatingActionButton child, View directTargetChild, View target, int nestedScrollAxes) {
    fab = child;
    return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL ||
            super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target,
                    nestedScrollAxes);
}



Runnable showRunnable = new Runnable() {
    @Override
    public void run() {
        fab.show();
    }
};


@Override
public void onNestedScroll(CoordinatorLayout coordinatorLayout, FloatingActionButton child,
                           View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) {
    super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed,
            dyUnconsumed);
     if (dyConsumed > 0 && child.getVisibility() == View.VISIBLE) {
        handler.removeCallbacks(showRunnable);
        handler.postDelayed(showRunnable,2000);
        child.hide();
    } 
    }
}