我想为我的应用程序添加夜间主题,但我已经浪费了将近三个小时,只是试图使我的导航抽屉中的文本和图标与黑暗背景一起变白。这是我在MainActivity.java
中的onCreate()
方法中尝试实现这一点的方式:
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger onItemClick of navigation menu
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// Checking if the item is in checked state or not, if not make it in checked state
if (menuItem.isChecked())
menuItem.setChecked(false);
else menuItem.setChecked(true);
if (nightMode == 0) {
SpannableString spanString = new SpannableString(menuItem.getTitle().toString());
spanString.setSpan(new ForegroundColorSpan(Color.WHITE), 0, spanString.length(), 0); // fix the color to white
menuItem.setTitle(spanString);
}
nightMode
布尔值并不重要,因为它是有效的。当夜间模式设置为打开(0)时,导航抽屉中选择的菜单项会变为白色。然而,这仅在选择每个项目时发生,显然很不方便。以下是我的 drawer_dark.xml 文件:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group
android:checkableBehavior="single">
<item
android:id="@+id/unitone"
android:checked="true"
android:icon="@drawable/one_white"
android:title="Classical Period" />
<item
android:id="@+id/unittwo"
android:checked="false"
android:icon="@drawable/two_white"
android:title="Postclassical Period" />
<item
android:id="@+id/unitthree"
android:checked="false"
android:icon="@drawable/three_white"
android:title="Early Modern Era" />
<item
android:id="@+id/unitfour"
android:checked="false"
android:icon="@drawable/four_white"
android:title="Dawn of Industrial Age" />
<item
android:id="@+id/unitfive"
android:checked="false"
android:icon="@drawable/five_white"
android:title="Modern Era" />
</group>
</menu>
我为每个项目使用透明背景上的白色图标,但是它们在导航抽屉的黑色背景上显示为黑色。我已经尝试查找通过xml更改文本颜色的解决方案,但我被困惑了,因为我不知道为什么会忽略这个问题。
有人能够提供一个动态解决方案来实现我的目标吗? 感谢所有帮助!
编辑:我没有使用第三方库,而是使用支持库中提供的NavigationView。以下是XML布局:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:elevation="7dp"
tools:context=".MainActivity"
android:fitsSystemWindows="true" >
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/ColorDark" />
<include layout="@layout/toolbar" />
</FrameLayout>
<android.support.design.widget.NavigationView
android:id="@+id/navigation_view"
android:background="#000"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/header"
app:menu="@menu/drawer" />
</android.support.v4.widget.DrawerLayout>