How can I Animate the color change of the statusbar and toolbar (like the new Calendar app does)

前端 未结 4 1619
逝去的感伤
逝去的感伤 2021-01-29 22:49

The new Google Calendar app has an animation I would like to do in my app. When you create a new event you can choose a color for the event. When you do, the statusbar and too

4条回答
  •  走了就别回头了
    2021-01-29 23:05

    I don't know how they achieved the ripple effect, but you can have a smooth color transition of both bars simultaneously with the following code.

    private void tintSystemBars() {
        // Initial colors of each system bar.
        final int statusBarColor = getResources().getColor(R.color.status_bar_color);
        final int toolbarColor = getResources().getColor(R.color.toolbar_color);
    
        // Desired final colors of each bar.
        final int statusBarToColor = getResources().getColor(R.color.status_bar_to_color);
        final int toolbarToColor = getResources().getColor(R.color.toolbar_to_color);
    
        ValueAnimator anim = ValueAnimator.ofFloat(0, 1);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                // Use animation position to blend colors.
                float position = animation.getAnimatedFraction();
    
                // Apply blended color to the status bar.
                int blended = blendColors(statusBarColor, statusBarToColor, position);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    getWindow.setStatusBarColor(blended);
                }
    
                // Apply blended color to the ActionBar.
                blended = blendColors(toolbarColor, toolbarToColor, position);
                ColorDrawable background = new ColorDrawable(blended);
                getSupportActionBar().setBackgroundDrawable(background);
            }
        });
    
        anim.setDuration(500).start();
    }
    
    private int blendColors(int from, int to, float ratio) {
        final float inverseRatio = 1f - ratio;
    
        final float r = Color.red(to) * ratio + Color.red(from) * inverseRatio;
        final float g = Color.green(to) * ratio + Color.green(from) * inverseRatio;
        final float b = Color.blue(to) * ratio + Color.blue(from) * inverseRatio;
    
        return Color.rgb((int) r, (int) g, (int) b);
    }
    

提交回复
热议问题