2

我使用首选项屏幕应用了暗模式:

  <ListPreference
        app:defaultValue="default"
        app:entries="@array/themes_labels"
        app:entryValues="@array/themes_color"
        app:key="theme"
        app:title="@string/Theme"
        app:useSimpleSummaryProvider="true"/>
  </PreferenceCategory>

和数组被定义为

<resources>
  <array name="themes_labels">
    <item>"Default"</item>
    <item>"Light"</item>
    <item>"Dark"</item>
  </array>

  <string-array name="themes_color">
    <item>"Default"</item>
    <item>"Light"</item>
    <item>"Dark"</item>
  </string-array>
</resources>

现在,在MainActivityonCreate 中,我想将主题更改为:

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
      AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
    } else {
      AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
    }
    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
//    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
    String theme = sharedPref.getString("theme", "Default");
//    Toast.makeText(this, theme, Toast.LENGTH_LONG).show();
    if (theme.equals("Dark")) {
      AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
    } else if (theme.equals("Light")) {
      AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
    } else {
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
      } else {
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
      }
    }

现在,问题是,使用Light或默认(即使defaultdark mode,例如电池节省),一切都很好。但是,如果选择了暗模式,那么我将面临很多问题,比如没有应用在片段中,甚至在某些情况下会导致崩溃。

我对android很陌生,不明白为什么会这样。请帮忙。

此处要求尝试解决此问题

4

0 回答 0