Reputation: 121
I have a toolbar and 2 styles (one dark and one light) and I use SharedPreferences to select one, but toolbar not work properly.
Activity:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
if (pref.getInt("DARK_MODE", 0) == 0) {
setTheme(R.style.AppTheme_Light);
} else {
setTheme(R.style.AppTheme_Dark);
}
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
}
Toolbar:
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="4dp"/>
Layout:
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<include layout="@layout/toolbar" />
</android.support.constraint.ConstraintLayout>
Style
<resources>
<style name="AppTheme.Light" parent="@android:style/Theme.Material.Light">
<item name="android:colorPrimary">@color/colorPrimary</item>
<item name="android:colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="android:colorAccent">@color/colorAccent</item>
<item name="android:titleTextColor">@color/white</item>
</style>
<style name="AppTheme.Dark" parent="@android:style/Theme.Material">
<item name="android:colorPrimary">@color/colorPrimary</item>
<item name="android:colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="android:colorAccent">@color/colorAccent</item>
<item name="android:actionMenuTextColor">@color/white</item>
</style>
</resources>
The app shows me 2 toolbar, one with menu and one without. If i comment setTheme(…) call all work properly.
Why? How can I resolve this problem?
Upvotes: 0
Views: 164
Reputation: 391
This is occurring because you are setting two toolbars:
setSupportActionBar(toolbar);
Use one or the other. In your case you should set the theme with no action bar Theme.AppCompat.Light.NoActionBar
You kind of answered the question yourself really "If i comment setTheme(…) call all works properly" :-D
The developer guides are always useful:
https://developer.android.com/training/appbar/setting-up
Upvotes: 3