如何设置暗黑模式

huangapple go评论151阅读模式
英文:

How to make a dark mode setting

问题

I am new to android development and I am looking to make a dark mode setting in my application.
For this I created a "preferences.xml" file which is displayed using a "SettingsActivity.java" file and a "SettingsFragment.java" file. I looked for a lot of solutions on the internet but none worked. Does anyone have a tutorial, example or solution?
Thanks

preferences.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <ListPreference
            android:key="@string/key_app_theme"
            android:title="@string/app_theme"
            android:summary=""
            android:icon="@drawable/ic_app_theme"
            android:entries="@array/pref_app_theme_entries"
            android:entryValues="@array/pref_app_theme_values"
            android:dialogTitle="@string/app_theme"
            android:defaultValue="1"/>

</PreferenceScreen>

arrays.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    
    <string-array name="pref_app_theme_entries">
        <item>@string/system</item>
        <item>@string/battery_saver</item>
        <item>@string/light</item>
        <item>@string/dark</item>
    </string-array>
    <string-array name="pref_app_theme_values">
        <item>1</item>
        <item>2</item>
        <item>3</item>
        <item>4</item>
    </string-array>
    
</resources>

activity_settings.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    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/activity_settings"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimary"
    tools:context=".SettingsActivity">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/activity_settings_toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:elevation="4dp"
        android:background="@color/colorPrimaryDark"
        app:title="@string/settings"
        app:titleTextColor="@color/colorAccent" />

    <FrameLayout
        android:id="@+id/activity_settings_fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/activity_settings_toolbar" />

</RelativeLayout>

SettingsActivity.java

public class SettingsActivity extends AppCompatActivity {

    private static Preference settings;

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

        if (findViewById(R.id.activity_settings_fragment_container) !=null) {
            if (savedInstanceState != null)
                return;

            getFragmentManager().beginTransaction().add(R.id.activity_settings_fragment_container, new SettingsFragment()).commit();
        }

        Toolbar toolbar = findViewById(R.id.activity_settings_toolbar);
        toolbar.setTitleTextAppearance(this, R.style.KaushanScriptRegular);
        toolbar.setNavigationIcon(R.drawable.ic_back);
        toolbar.setNavigationOnClickListener(view -> {
            Intent intent = new Intent(SettingsActivity.this, MainActivity.class);
            startActivity(intent);
            overridePendingTransition(R.anim.swipe_right_enter, R.anim.swipe_right_exit);
        });
    }
}

SettingsFragment.java

public class SettingsFragment extends PreferenceFragment {

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        addPreferencesFromResource(R.xml.preferences);
    }
}
英文:

I am new to android development and I am looking to make a dark mode setting in my application.
For this I created a "preferences.xml" file which is displayed using a "SettingsActivity.java" file and a "SettingsFragment.java" file. I looked for a lot of solutions on the internet but none worked. Does anyone have a tutorial, example or solution?
Thanks

preferences.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;PreferenceScreen xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;

    &lt;ListPreference
            android:key=&quot;@string/key_app_theme&quot;
            android:title=&quot;@string/app_theme&quot;
            android:summary=&quot;&quot;
            android:icon=&quot;@drawable/ic_app_theme&quot;
            android:entries=&quot;@array/pref_app_theme_entries&quot;
            android:entryValues=&quot;@array/pref_app_theme_values&quot;
            android:dialogTitle=&quot;@string/app_theme&quot;
            android:defaultValue=&quot;1&quot;/&gt;

&lt;/PreferenceScreen&gt;

arrays.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;resources&gt;
    
    &lt;string-array name=&quot;pref_app_theme_entries&quot;&gt;
        &lt;item&gt;@string/system&lt;/item&gt;
        &lt;item&gt;@string/battery_saver&lt;/item&gt;
        &lt;item&gt;@string/light&lt;/item&gt;
        &lt;item&gt;@string/dark&lt;/item&gt;
    &lt;/string-array&gt;
    &lt;string-array name=&quot;pref_app_theme_values&quot;&gt;
        &lt;item&gt;1&lt;/item&gt;
        &lt;item&gt;2&lt;/item&gt;
        &lt;item&gt;3&lt;/item&gt;
        &lt;item&gt;4&lt;/item&gt;
    &lt;/string-array&gt;
    
&lt;/resources&gt;

activity_settings.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;RelativeLayout
    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
    android:id=&quot;@+id/activity_settings&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    android:background=&quot;@color/colorPrimary&quot;
    tools:context=&quot;.SettingsActivity&quot;&gt;

    &lt;androidx.appcompat.widget.Toolbar
        android:id=&quot;@+id/activity_settings_toolbar&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:elevation=&quot;4dp&quot;
        android:background=&quot;@color/colorPrimaryDark&quot;
        app:title=&quot;@string/settings&quot;
        app:titleTextColor=&quot;@color/colorAccent&quot; /&gt;

    &lt;FrameLayout
        android:id=&quot;@+id/activity_settings_fragment_container&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;match_parent&quot;
        android:layout_below=&quot;@id/activity_settings_toolbar&quot; /&gt;

&lt;/RelativeLayout&gt;

SettingsActivity.java

public class SettingsActivity extends AppCompatActivity {

    private static Preference settings;

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

        if (findViewById(R.id.activity_settings_fragment_container) !=null) {
            if (savedInstanceState != null)
                return;

            getFragmentManager().beginTransaction().add(R.id.activity_settings_fragment_container, new SettingsFragment()).commit();
        }

        Toolbar toolbar = findViewById(R.id.activity_settings_toolbar);
        toolbar.setTitleTextAppearance(this, R.style.KaushanScriptRegular);
        toolbar.setNavigationIcon(R.drawable.ic_back);
        toolbar.setNavigationOnClickListener(view -&gt; {
            Intent intent = new Intent(SettingsActivity.this, MainActivity.class);
            startActivity(intent);
            overridePendingTransition(R.anim.swipe_right_enter, R.anim.swipe_right_exit);
        });
    }
}

SettingsFragment.java

public class SettingsFragment extends PreferenceFragment {

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        addPreferencesFromResource(R.xml.preferences);
}

答案1

得分: 2

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.night_mode) {
        // 获取应用的夜间模式状态。
        int nightMode = AppCompatDelegate.getDefaultNightMode();
        // 为重新启动的活动设置主题模式。
        if (nightMode == AppCompatDelegate.MODE_NIGHT_YES) {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
        } else {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
        }
        // 重新创建活动以应用主题更改。
        recreate();
    }
    return super.onOptionsItemSelected(item);
}

还可以查看[主题样式检查][1]

[1]: https://developer.android.com/guide/topics/ui/look-and-feel/themes
英文:
@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.night_mode) {
            // Get the night mode state of the app.
            int nightMode = AppCompatDelegate.getDefaultNightMode();
            //Set the theme mode for the restarted activity
            if (nightMode == AppCompatDelegate.MODE_NIGHT_YES) {
                AppCompatDelegate.setDefaultNightMode
                        (AppCompatDelegate.MODE_NIGHT_NO);
            } else {
                AppCompatDelegate.setDefaultNightMode
                        (AppCompatDelegate.MODE_NIGHT_YES);
            }
// Recreate activity for the theme change to take effect.
            recreate();

        }
        return super.onOptionsItemSelected(item);
    }

Also, you can go with Check Theme Style

答案2

得分: 0

请参考以下视频以开发夜间模式:
Night/Dark Mode Tutorial

这个视频使用Kotlin进行演示,但将其翻译成Java相对简单。
要监听SharedPreferences的更改:

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
int theme = Integer.valueOf(sharedPreferences.getString("theme", "1"));
switch (theme) {
    case 3:
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
        break;
    case 4:
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
        break;
    case 2:
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
        break;
    default:
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
}

(假设您的主题设置的Preference键是 "theme"。)
其余的代码位于XML文件中,在使用Java替代Kotlin时不需要更改。

英文:

Refer to this video for developing a Night Mode:
Night/Dark Mode Tutorial

It's given in Kotlin but the translation into Java is simple enough.
For listening to SharedPreferences:

int theme = Integer.valueOf(sharedPreferences.getString(&quot;theme&quot;, &quot;1&quot;));
switch (theme) {
	case 3 :
		AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
		break;
	case 4 :
		AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
		break;
	case 2 :
		AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
		break;
	default :
		AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);

(Assuming that the Preference key for your theme setting is "theme".)
The rest of the code is in XML files so it is unaltered when Java is used instead of Kotlin.

huangapple
  • 本文由 发表于 2020年8月12日 04:30:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/63365949.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定