滚动事件期间更改操作栏alpha

时间:2014-09-03 14:07:34

标签: android android-actionbar alpha onscrolllistener

我尝试在主ScrollView的滚动事件中在操作栏上创建淡入淡出alpha:

我试过了:

//Active Overlay for ActionBar before set my content in the activity
getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);

//create a new Drawable for the AB background
final ColorDrawable newColor = new ColorDrawable(getResources().getColor(R.color.primaryColor));
newColor.setAlpha(0);
getActionBar().setBackgroundDrawable(newColor);

//create a OnScrollListener to get ScrollY position
final ScrollView mainScrollView = (ScrollView) findViewById(R.id.place_detail_scrollView);
mainScrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
            @Override
            public void onScrollChanged() {
                final int scrollY = mainScrollView.getScrollY();
                final int boundY = 300;
                final float ratio = (float) (scrollY/boundY) ;
                newColor.setAlpha((int)(ratio*255));
            }
        });

理论上,我的操作栏会在ScrollView的0到300位之间淡化其alpha值。不幸的是,我的AB每次都仍然透明......任何想法?

1 个答案:

答案 0 :(得分:4)

我发现了问题,我使用了一个预先的Jelly Bean设备,所以这个问题有一个解决方法。

事实上,对于pre-JELLY_BEAN_MR1设备,我们必须在Callback的{​​{1}}方法中添加以下onCreate(Bundle)

Drawable

然后设置回调

private Drawable.Callback mDrawableCallback = new Drawable.Callback() {
    @Override
    public void invalidateDrawable(Drawable who) {
        getActionBar().setBackgroundDrawable(who);
    }

    @Override
    public void scheduleDrawable(Drawable who, Runnable what, long when) {
    }

    @Override
    public void unscheduleDrawable(Drawable who, Runnable what) {
    }
};

就是这样,感谢Cyril Mottier这个!