防止 FloatingActionButton 在 CoordinatorLayout、ViewPager、Fragment 中可见

Prevent FloatingActionButton became visible within CoordinatorLayout, ViewPager, Fragment

我在 CoordinatorLayout 中实现了 ViewPagerFloatingActionButtonFloatingActionButton 有一个 layout_behavior 设置为自定义 。在滑动寻呼机时,fab 成功地改变了可见性(动画),在滚动嵌套视图时也是如此。我已经实现了任何必要的支持库 (23.3.0)。

寻呼机显示 2 Fragments:

  1. RecyclerView(必须表现得很好)
  2. NestedScrollView(不得显示 fab)

在页面更改时,activity 询问子片段(界面)是否显示 fab。这很好用,但是在第二个片段中向下滚动滚动视图时,fab 再次可见。

如何防止向下滚动 NestedScrollView 时再次显示 fab?

好的,我从 G+ 用户那里得到了答案(致谢 Christophe Beyls)!

正在检索 CoordinatorLayout.Behavior 主实例 activity(或主片段):

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    CoordinatorLayout rootView = (CoordinatorLayout) inflater.inflate(R.layout.main, container, false);
    FloatingActionButton fab = (FloatingActionButton) mRootView.findViewById(R.id.fab);
    CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
    CoordinatorLayout.Behavior b = lp.getBehavior();

    if (b instanceof ScrollAwareFABBehavior) { // my custom behavior
        // saving ref for later use
        mFABBehavior = (ScrollAwareFABBehavior) b;
    }

    // do other stuff

    return rootView;
}

ScrollAwareFABBehavior.java中添加:

public class ScrollAwareFABBehavior extends FloatingActionButton.Behavior {
    private boolean mFabUserHidden = false;

    // other stuff in here

    /**
     * Overrides the default FAB show/hide functionality
     *
     * @param hidden    TRUE to stay hidden, false otherwise
     */
    public void stayHidden(boolean hidden) {
        mFabUserHidden = hidden;
    }

    @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 && !this.mIsAnimatingOut && child.getVisibility() == View.VISIBLE) {
            animateOut(child);
        } else if (dyConsumed < 0 && !mFabUserHidden && child.getVisibility() != View.VISIBLE) {
            animateIn(child);
        }
    }

    // do other stuff

}

ViewPager.OnPageChangeListener 中,您可以为每个片段设置 fab 是否可见。

也许它会对遇到同样问题的人有所帮助!!