滚动列表视图时如何拥有控制操作栏的能力?

How can I have the ability control action bar while scrolling the listview?

我正在使用 appCompat 操作栏。我尝试制作一个像 instagram 这样的主页,而用户向下滚动操作栏是隐藏的,反之亦然。

下面的代码是在滚动列表视图时隐藏和显示动作的最基本方法

int mLastFirstVisibleItem = 0;

if (view.getId() == mListView.getId()) {
    final int currentFirstVisibleItem = mListView.getFirstVisiblePosition();

    if (currentFirstVisibleItem > mLastFirstVisibleItem) {
        getSupportActionBar().hide();
    } else if (currentFirstVisibleItem < mLastFirstVisibleItem) {
        getSupportActionBar().show();
    }

     mLastFirstVisibleItem = currentFirstVisibleItem;
}

问题是当我缓慢滚动列表视图时,操作栏将保持隐藏和显示 repeatly.It 无法让我控制我想要隐藏或显示操作栏的程度。我想要的是当我向下或向上滚动列表视图时,操作栏最终将跟随手势,当用户从屏幕上移开时,它将隐藏或显示取决于屏幕上保持可见的操作栏的大小。

例如,当我向下滚动 2px 时,操作栏将上升或隐藏 2px。如果屏幕上的操作栏大小为 20px,而操作栏大小为 50px,它将像下面的代码一样隐藏它。

//this is just a demo of how I want the action bar to work not any type of programming language
//visibleActionBarOnscreen is the actionbarsize remain on screen

if(visibleActionBarOnScreen > actiobarSize/2){
    //show the action bar
}else{
    //hide the action bar
}

Push out/pull in ActionBar when ListView is scrolled 这个link 教你如何控制操作栏。但我仍然不知道如何使它 done.In 另外它不会自动重新调整操作栏以完全隐藏或显示,而是让操作栏在屏幕上显示一半,同时用户从屏幕上移开。请帮助我完成这项工作,我将 100% 感激!

如果您想要一个 smooth-transitioning 栏,您可能想要使用布局(可能是水平线性布局,将内容放入操作栏中)来实现您的 自己的 自定义操作栏水平)和 animating/transitioning 您的 app-header 通过设置负边距将其拉出屏幕顶部。 (这是具有更多可定制性的替代解决方案。)

这是动画布局边距的示例:Change Left Margin Using Animation(您必须将其更改为上边距)

但是,这不会像你说的那样 "sticking" action-bar(它不会 保持 在 2px 或中间等).要实现 "sticking" 滚动操作栏,您需要覆盖 ListView 或 CustomScrollView 上的 OnScrollListener() 并像这样进行一些计算:

int scrollpos = (int)view.getScrollY();
if(scrollpos<70) { //trigger scroll movement
    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)findViewById(R.id.ListView).getLayoutParams();
    params.topMargin = -scrollpos;
    //if scrollpos = 0, then topMargin will = 0, completely visible.
    //if scroll is past 70, then topMargin will = -70, completely hidden.
    //assuming your action-bar is 70px
    findViewById(R.id.ListView).setLayoutParams(params);
}

您实际上必须通过获取和设置 LayoutParams 来设置 topMargin,我没有在上面包含它。我远离任何 Java IDE,所以我暂时无法编译代码。

希望这对您有所帮助,