用于更改操作栏样式并通过应用程序保留的按钮

时间:2015-09-01 17:33:52

标签: android android-actionbar

我是Android开发的新手,我正在创建一个简单的应用程序来训练。

在这个应用程序中,我想在操作栏菜单中有一个按钮,如果按下该按钮,将改变操作栏颜色。我有点设法在我的主要活动中使用静态变量和上面列出的switchActionBarColor()方法实现了这一点。但我的问题是当我去一个新的活动:操作栏改变颜色,我没有按下菜单按钮。当我回到我的主要活动时,它不再是彩色的了。我希望Action Bar风格能够在应用程序中持续存在,我觉得我的方法根本不适合。据你说,最好的办法是什么?感谢

public class MainActivity extends Activity {

protected static int color = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

/** Called when the user clicks the add_contact button */
public void addContact(View view) {
    Intent intent = new Intent(this, AddContactActivity.class);
    startActivity(intent);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main_activity_actions, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle presses on the action bar items
    switch (item.getItemId()) {
        case R.id.action_search:
            openSearch();
            return true;
        case R.id.change_color:
            switchActionBarColor();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

protected void switchActionBarColor() {
    ActionBar bar = getActionBar();

    if (bar == null)
        return ;
    switch (color) {
        case 0:
            bar.setBackgroundDrawable(new ColorDrawable(getResources()
                    .getColor(R.color.actionbar_background_1)));
            break ;
        case 1:
            bar.setBackgroundDrawable(new ColorDrawable(getResources()
                    .getColor(R.color.actionbar_background_2)));
            break ;
        case 2:
            bar.setBackgroundDrawable(new ColorDrawable(getResources()
                    .getColor(R.color.actionbar_background_3)));
            break ;
        case 3:
            bar.setBackgroundDrawable(new ColorDrawable(getResources()
                    .getColor(R.color.actionbar_background_default)));
            break ;
    }
    color++;
    if (color == 4)
        color = 0;
    return ;
}

}

1 个答案:

答案 0 :(得分:0)

您可以使用SharedPreferences(https://developer.android.com/reference/android/content/SharedPreferences.html)保存并加载颜色指示器,并在活动的onResume中设置ActionBar的颜色。