水平滚动时更改操作栏渐变背景颜色

时间:2015-03-08 05:57:07

标签: android

我想在水平滚动的同时更改ActionBar的背景(渐变色)。

我创建ViewPager的子类并覆盖onInterceptTouchEvent方法以获取方向(左 - 右)并尝试获取滚动的百分比。 (我从0%开始,当页面改变时,它是我的100%)。

我使用此百分比将操作栏背景从一种颜色转换为其他颜色。示例:蓝色 - >绿色RGB(0,0,255)到(0,238,0)。

    @Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    float x = ev.getX();

     switch (ev.getAction()){
         case MotionEvent.ACTION_DOWN:
             mStartDragX = x;
             break;

        case MotionEvent.ACTION_MOVE:
                if (mStartDragX > x){
                    //Left scroll
                    float percent = (mStartDragX - x) / screen_width * 100;
                    changeColorActionBar(true, percent);
                    return super.onInterceptTouchEvent(ev);
                }
                else if (mStartDragX < x){
                    //Right scroll
                    float percent = (x - mStartDragX)  / screen_width * 100;
                    changeColorActionBar(false, percent);
                    return super.onInterceptTouchEvent(ev);
                }
                break;
        }
        return super.onInterceptTouchEvent(ev);
}

问题是当我抬起手指时这种方法有效。但如果我在不改变页面的情况下反复滚动到左侧,背景会从蓝色变为绿色。

所以我不知道我必须覆盖的方法,以便在不抬起手指的情况下评估位移。

感谢。

1 个答案:

答案 0 :(得分:1)

使用此CustomViewPager代替您,您必须覆盖onTouch,因为这将在您滚动时始终请求:


enter image description here enter image description here


CustomViewPager.class

public class CustomViewPager extends ViewPager {

float mStartDragX;
int screen_width;

android.support.v7.app.ActionBar actionBar;

public CustomViewPager(Context context) {
    super(context, null);
}

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

}

public void setActivity(MainActivity activity) {
    this.screen_width = activity.getWindowManager().getDefaultDisplay().getWidth();
    this.actionBar = activity.getSupportActionBar();
}

@Override
public boolean onTouchEvent(MotionEvent ev) {
    float x = ev.getX();

    switch (ev.getAction()) {
        case MotionEvent.ACTION_DOWN:
            mStartDragX = x;
            break;

        case MotionEvent.ACTION_MOVE:
            if (mStartDragX > x) {
                //Left scroll
                float percent = (mStartDragX - x) / screen_width * 100;
                changeColorActionBar(true, percent);
            } else if (mStartDragX < x) {
                //Right scroll
                float percent = (x - mStartDragX) / screen_width * 100;
                changeColorActionBar(false, percent);
            }
    }
    return super.onTouchEvent(ev);
}

public void changeColorActionBar(boolean toRight, float percent) {

    int result = (int) ((percent * 255) / 100);
    int part = 255 - result;

    if (toRight) {
        actionBar.setBackgroundDrawable(new ColorDrawable(Color.rgb(0, part, result)));
    } else {
        actionBar.setBackgroundDrawable(new ColorDrawable(Color.rgb(0, result, part)));
    }
}

}

相关问题