如何使用scrollview隐藏/显示片段中的操作栏

时间:2016-07-02 09:56:00

标签: android android-viewpager material-design

在下面的scrollview片段中隐藏或显示操作栏的问题是我的代码

scView=(ScrollView)view.findViewById(R.id.vertical_scrollview_id);
        scView.getViewTreeObserver().addOnScrollChangedListener(new OnScrollChangedListener() {

            @Override
            public void onScrollChanged() {
                // TODO Auto-generated method stub
                 if(scView.getScrollY()>120){
                     if(action.isShowing()){
                         action.hide();
                     }
                 }else if(scView.getScrollY()<50){
                     if(!action.isShowing()){
                         action.show();                          
                     }
                 }
                   return;
            }
        });

我使用了材料设计和查看寻呼机

2 个答案:

答案 0 :(得分:0)

创建ViewTreeObserver.OnScrollChangedListener

的自定义实现
public abstract class ScrollViewScrollListener implements
                      ViewTreeObserver.OnScrollChangedListener {

    private static final int SCROLL_THRESHOLD = 30;
    private ScrollView mScrollView;
    private int mScrollPosition;

    /**
     * Default constructor
     * @param scrollView to calculate the distance scrolled.
     */
    public ScrollViewScrollListener(ScrollView scrollView) {
        mScrollView = scrollView;
        mScrollPosition = scrollView.getScrollY();
    }

    @Override
    public final void onScrollChanged() {
        int scrollY = mScrollView.getScrollY();
        if (Math.abs(scrollY - mScrollPosition) > SCROLL_THRESHOLD) {
            onScrolled(scrollY - mScrollPosition < 0);
            mScrollPosition = scrollY;
        }
    }

    /**
     * Called when the attached scrollview has been scrolled
     * @param scrolledUp true indicating the scroll view has scrolled in upward direction,
     *                   false indicating a downward scroll
     */
    public abstract void onScrolled(boolean scrolledUp);
}

现在将此侦听器附加到ScrollView

scView.getViewTreeObserver().addOnScrollChangedListener(new ScrollViewScrollListener(scView) {
        @Override
        public void onScrollChanged(boolean scrolledUp) {
            if(scrolledUp) {
                //scrolled up show the actionbar
            } else {
                //scrolled down hide the actionbar
            }
        }
    });

答案 1 :(得分:0)

您是否为此目的尝试过CoordinatorLayout?

这里有一个解释它的教程。

http://mzgreen.github.io/2015/02/15/How-to-hideshow-Toolbar-when-list-is-scroling%28part1%29/