在创建时更改工具栏和 AppBarLayout 背景

Change Toolbar & AppBarLayout Background onCreate

我正在尝试为我的应用程序设置 2 个主题选项,深色和浅色。选择深色主题后,我使用 sharedpreference 来保存并在启动时应用主题。但是当我尝试像这样更改工具栏和 appBarLayout 的背景颜色时:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
    long currentTheme = sharedPref.getInt(getString(string.current_theme), 0);
    if (currentTheme == 0) {
        this.setTheme(R.style.AppTheme_NoActionBar);
    }
    if (currentTheme == 1) {
        this.setTheme(R.style.AppTheme_NoActionBar_Dark);
        Toolbar toolbar = (Toolbar) findViewById(id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setBackgroundColor(getResources().getColor(ActionbarDark));
    }

Logcat returns 错误:java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.Toolbar.setBackgroundColor(int)' on a null object reference

我不明白为什么

更新:通过使用@Nilesh Rathod 的答案并在设置内容视图之前更改 activity 的主题,然后在设置内容视图后更改工具栏和 AppBarLayout 的主题来修复它。

您在工具栏 findViewById 中错过了 R

应该喜欢下面

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

像这样更改您的代码

Toolbar toolbar;
    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
    long currentTheme = sharedPref.getInt(getString(string.current_theme), 0);
    if (currentTheme == 0) {
        this.setTheme(R.style.AppTheme_NoActionBar);

    }
    if (currentTheme == 1) {
        this.setTheme(R.style.AppTheme_NoActionBar_Dark);
        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(0xff00DDED));
    }
    setContentView(R.layout.activity_main);
    registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));


    android.app.FragmentManager fragmentmanager = getFragmentManager();
    fragmentmanager.beginTransaction()
            .replace(R.id.content_frame
                    , new FirstFragment())
            .commit();

    DrawerLayout drawer = (DrawerLayout) findViewById(id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, string.navigation_drawer_open, string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
    navigationView.getMenu().getItem(0).setChecked(true);
}