APP实用开发—ScrollView滑动标题栏颜色渐变

APP实用开发—ScrollView滑动标题栏颜色渐变_第1张图片

从图中我们应该就能了解到,其实这些好像就那么回事,拿到高度,然后设置透明度就行了,其实,是这个样子的

首先,我们要知道设置View的透明度的代码

自定义ScrollView + toolbar渐变
1、自定义一个类,继承自ScrollView,并重写它的 onScrollChanged 方法;
2、在 onScrollChanged 中获取 ScrollView 在Y轴的移动距离,并根据此距离改变 Toolbar(标题栏) 的透明度。

 toolbar.setBackgroundColor(Color.argb(alpha,109,90,123));

参数设置的是透明度的变化值为0~255,颜色数嘛是吧。

然后看看获取变化距离区间的代码

headHeight= headView.getMeasuredHeight()-toolbar.getMeasuredHeight();

这样,我们就拿到距离的代码了,现在两样都齐全了,怎样才能将他们关联起来呢,我们想想,当前滚动的ScrollView的Y值去减去这个headHeight,这个相差值只允许他在headHeight的高度去变化,如果ScrollView滑动的距离超出这个高度的话,那么我们直接设置alpha为255直接显示变透明,如果这个ScrollView滑动的到顶部时,我们直接设置alpha为0为透明,我们首先拿到这个变化的距离,然后去除以这个headHeight高度拿到这个百分比,然后去乘上255拿到同等比例中的透明度的值,记得这个数值都得是float类型,高度也是,要是int的话这样相除的话就变成0了。

alpha=((float)(getScrollY()-headHeight)/headHeight)*255

拿到这个透明度后就可以设置进去了,思路就是这么简单,现在来贴下代码。

class AlphaTitleScrollView extends ScrollView {
    public static final String TAG = "AlphaTitleScrollView";
    private int mSlop;
    private Toolbar toolbar;
    private ImageView headView;

    public AlphaTitleScrollView(Context context, AttributeSet attrs,
                                int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    public AlphaTitleScrollView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);

    }

    public AlphaTitleScrollView(Context context) {
        this(context, null);
    }

    private void init(Context context) {
        // mSlop = ViewConfiguration.get(context).getScaledDoubleTapSlop();
        mSlop = 10;
        Log.i(TAG, mSlop + "");
    }

    /**
     *  @param headLayout
     *            头部布局
     * @param imageview
     * @param toolbar
     */
    public void setTitleAndHead(Toolbar toolbar, ImageView headView) {
        this.toolbar = toolbar;
        this.headView = headView;
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        float headHeight = headView.getMeasuredHeight()
                - toolbar.getMeasuredHeight();
        int alpha = (int) (((float) t / headHeight) * 255);
        if (alpha >= 255)
            alpha = 255;
        if (alpha <= mSlop)
            alpha = 0;
        toolbar.setBackgroundColor(Color.argb(alpha,109,90,123));

        super.onScrollChanged(l, t, oldl, oldt);
    }
}
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar to = (Toolbar) findViewById(R.id.tool);
        setSupportActionBar(to);
        getSupportActionBar().setTitle("");
        AlphaTitleScrollView scroll = (AlphaTitleScrollView) findViewById(R.id.scrollview);

        ImageView head = (ImageView) findViewById(R.id.head);
        scroll.setTitleAndHead(to, head);
        to.setBackgroundColor(Color.argb(0,202,230,202));


    }
}

你可能感兴趣的:(Android-实用开发)