I'm trying to change the background color of android action bar at runtime, according to an image VibrantColor.
I found some references, but neither worked for me.
Change action bar color in android
How do I change the background color of the ActionBar of an ActionBarActivity using XML?
I have this code to get the color from the image, and it works.
public int getImageColor(Bitmap foto) {
Palette palette = Palette.generate(foto);
List<Palette.Swatch> swatchList = palette.getSwatches();
int maiorPopulação = 0;
int color = 0;
for (Palette.Swatch sw : swatchList){
if (sw.getPopulation() > maiorPopulação) {
maiorPopulação = sw.getPopulation();
color = sw.getRgb();
}
}
return palette.getVibrantColor(color);
}
Then I try to set the returned color to the ActionBar:
public static void alteraCor(Fragment fragmento, int color) {
ActionBarActivity atividade = (ActionBarActivity)fragmento.getActivity();
android.support.v7.app.ActionBar actionBar = atividade.getSupportActionBar();
if ( fragmento instanceof Detalhes )
actionBar.setBackgroundDrawable(new ColorDrawable(Color.rgb(
Color.red(color),
Color.green(color),
Color.blue(color)
)));
else
actionBar.setBackgroundDrawable(new ColorDrawable(fragmento.getResources().getColor(R.color.fundoEscuro)));
}
I called alteraCor
from onCreate
and from onAttach
on Fragment, but neither of them worked.
EDIT:
I use the folowing Style:
<style name="VendasFacil" parent="@style/Theme.AppCompat">
<item name="android:textColor">@color/Fonte</item>
<item name="android:background">@color/fundoPrimeiroPlano</item>
<item name="android:windowBackground">@color/fundoPrimeiroPlano</item>
<item name="actionBarTheme">@style/VendasFacil.ActionBar</item>
<item name="android:actionBarTheme" tools:ignore="NewApi">@style/VendasFacil.ActionBar</item>
</style>
<style name="VendasFacil.ActionBar" parent="@style/Widget.AppCompat.ActionBar">
<item name="android:background">@color/fundoEscuro</item>
<item name="android:displayOptions">showHome|homeAsUp|showTitle</item>
<item name="displayOptions">showHome|homeAsUp|showTitle</item>
<item name="android:homeAsUpIndicator">@drawable/ic_launcher</item>
<item name="homeAsUpIndicator">@drawable/ic_drawer</item>
</style>
I do not have the color I want to use as background previously to put it in a style file. It is as if the color was defined by the user at runtime.