Search code examples
androidandroid-layoutuser-interfacematerial-designstatusbar

How to change color of status bar dynamically in android based upon the foreground image?


I want to implement the same feature as we can see in WhatsApp, while seeing a person's profile the color of the status bar changes based upon the color of the image.


Solution

  • It's called Pallete, use the below function, just pass your bitmap image

      private void setUpPalette(Bitmap bitmap) {
       // you passed your Bitmap image;
        Palette.from(bitmap).
                generate(new Palette.PaletteAsyncListener() {
                    @Override
                    public void onGenerated(Palette palette) {
                        if (palette != null) {
    
                           //default color is yellow
                           // set the color to toolbar, whatever
                            int extColor = palette.getVibrantColor(ContextCompat.getColor(MainActivity.this, R.color.yellow));
                             if (getWindow() != null) {
                                    getWindow().setStatusBarColor(ContextCompat.getColor(this, extColor));
                                    }
                        } else {
                             if (getWindow() != null) {
                                        getWindow().setStatusBarColor(ContextCompat.getColor(this, R.color.fail_safe));
                                                        }
                        }
                    }
                });
    }