Search code examples
androidbackground-colorandroid-drawableandroid-toolbarandroid-collapsingtoolbarlayout

Dynamically get primary color of drawable to set toolbar color


I have an android app with a collapsing toolbar layout for a detailed view. I'm trying to dynamically set the color of the toolbar, according to the primary color of the drawable that was passed in.

I know this is possible with the new material guidelines, but I can't find any documentation on it.


Solution

  • Okay, so I started with what Akasha stated but generate is deprecated in latest version. So I ended up doing the following.

    // Get reference to icon drawable
    Drawable iconDrawable = mPackageHelper.getAppIcon(mApp.getAppPackage());
    
    Bitmap iconBitmap = ((BitmapDrawable) iconDrawable).getBitmap();
    
    Palette iconPalette = Palette.from(iconBitmap).maximumColorCount(16).generate();
    
    int primaryColorInt = iconPalette.getVibrantColor(0x000000);
    
    mToolbar.setBackgroundColor(primaryColorInt);
    collapsingToolbar.setBackgroundColor(primaryColorInt);