使用CollapsingToolbarLayout时更改FloatingButton的行为

时间:2015-11-26 18:40:15

标签: android behavior android-collapsingtoolbarlayout

我正在开发一个应用,其中我有一个CollapsingToolbarLayout的页面和ImageView(用户的图片)代替FloatingActionButton

默认行为是在CollapsingToolbarLayout完全隐藏时隐藏图像,但我想要一个不同的行为: 我希望当用户向上滚动页面时,图像会继续前进,但速度很慢。因此,当它完全隐藏时,图像会出现在工具栏下方,就像这样(只是一个更好的理解的例子):

之前: enter image description here

后: enter image description here

有办法做到这一点吗?

1 个答案:

答案 0 :(得分:1)

您需要扩展CoordinatorLayout.Behavior<FloatingActionButton>并覆盖方法onDependentViewChanged上的行为。

public class ScrollingFABBehavior extends CoordinatorLayout.Behavior<FloatingActionButton> {

    private int toolbarHeight;

    public ScrollingFABBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);

        this.toolbarHeight = GenericUtils.getActionBarHeight(context);
    }

    @Override
    public boolean layoutDependsOn(CoordinatorLayout parent, FloatingActionButton fab, View dependency) {
        return dependency instanceof AppBarLayout || dependency instanceof Snackbar.SnackbarLayout;
    }

    @Override
    public boolean onDependentViewChanged(CoordinatorLayout parent, FloatingActionButton fab, View dependency) {
        if (dependency instanceof AppBarLayout) {
            CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
            int fabBottomMargin = lp.bottomMargin;
            int distanceToScroll = fab.getHeight() + fabBottomMargin;
            float ratio = dependency.getY() / (float) toolbarHeight;

            fab.setTranslationY(-distanceToScroll * ratio);

            return true;
        }

        if (dependency instanceof Snackbar.SnackbarLayout) {
            float translationY = Math.min(0, dependency.getTranslationY() - dependency.getHeight());

            fab.setTranslationY(translationY);

            return true;
        }

        return false;
    }

}

您可以在此处查看开源应用的示例:https://github.com/nowsecure/android-vts/blob/master/app/src/main/java/fuzion24/device/vulnerability/test/ScrollingFABBehavior.java