[英]Change background color of android action bar at runtime
根據圖像VibrantColor,我正在嘗試在運行時更改android操作欄的背景顏色。
我找到了一些參考,但都沒有為我工作。
我有這段代碼可以從圖像中獲取顏色,並且可以正常工作。
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);
}
然后,我嘗試將返回的顏色設置為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)));
}
我從onCreate
和Fragment的onAttach
調用了alteraCor
,但它們都onAttach
。
編輯:
我使用以下樣式:
<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>
我之前沒有想要用作背景顏色的顏色放入樣式文件中。 好像顏色是由用戶在運行時定義的。
您將需要為此創建樣式。 然后,您可以在運行時更改樣式以使操作欄反映它。
這可能會很有用: http : //developer.android.com/guide/topics/ui/actionbar.html#AdvancedStyles
這是樣式更改操作欄顏色的示例:
<style name="MyActionBar" parent="@android:style/Widget.Holo.Light.ActionBar">
<item name="android:background">ANY_HEX_COLOR_CODE</item>
</style>
您可以使用Android操作欄樣式生成器 。 它生成XML文件。 復制到您的項目。 簡單又好。
嘿,您的代碼中似乎有一個小錯誤:
actionBar.setBackgroundDrawable(new ColorDrawable(Color.rgb(
Color.red(color),
Color.green(color),
Color.blue(color)
)));
您正在將r的g和b值設置為顏色的十六進制值。 您需要做的只是:
actionBar.setBackgroundDrawable(new ColorDrawable(color));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.