从首选项以编程方式更改操作栏背景颜色

时间:2012-11-03 15:54:32

标签: android android-actionbar color-picker

我在应用中的设置中添加了颜色选择器首选项,因此用户可以选择ActionBar的背景颜色(我正在使用ActionBarSherlock)。理想情况下,我想在不让用户重新启动应用程序的情况下更改颜色,我假设这意味着添加代码以更改onResumeActivityFragment中的颜色。但是,当我第一次点击某个活动时,颜色变化会起作用,但如果我回到它,使用设备上的后退按钮或ActionBar本身,颜色似乎没有设置并且是透明的。

这是我用来设置背景颜色的代码。我尝试将其添加到onCreate以及onResume

public class MyActivity extends SherlockActivity {

   @Override
    public void onCreate(final Bundle icicle) 
    {
        super.onCreate(icicle);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);        
        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(PreferenceManager.getDefaultSharedPreferences(this).getInt("app_color", getResources().getColor(R.color.app_color))));
    }

    @Override
    public void onResume()
    { 
        super.onResume();

        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(PreferenceManager.getDefaultSharedPreferences(this).getInt("app_color", getResources().getColor(R.color.app_color))));
    }
}

app_color是颜色选择器首选项的名称,也有默认颜色,存储在colors值文件中。我还有一个TextView页脚没有相同的问题并保留颜色。

1 个答案:

答案 0 :(得分:1)

我有同样的问题,我想出的可能不是最好的解决方案,但至少暂时对我有用。如果主题已更改,我会使用以下方法检入onRestart(在您的应用中,您将检查背景颜色是否已更改),如果是,则启动活动,如下面的代码片段所示。在我的应用程序中,我将此方法放在应用程序类中,因为我在每个活动中都使用它。

public static void restartOnThemeSwitch(Activity act) {

    String currentTheme = getThemeName(act.getTheme());

    String prefTheme = (prefs.getString(THEME, "dark"));

    if (currentTheme.equalsIgnoreCase(prefTheme) == false) {


        Intent it = act.getIntent();
        it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        act.startActivity(it);

    }

}
相关问题