Изменить тему android, используя настройки и настройки - PullRequest
1 голос
/ 14 января 2020

Я пытаюсь реализовать тему android (используя <style name="AppTheme" parent="Theme.AppCompat.DayNight">).

Теперь из SettingActivity я пытаюсь выбрать тему. Я определил SettingsActivity как:

public class SettingsActivity extends AppCompatActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.settings_activity);
    getSupportFragmentManager()
        .beginTransaction()
        .replace(R.id.settings, new SettingsFragment())
        .commit();
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
      actionBar.setDisplayHomeAsUpEnabled(true);
    }
  }

  public static class SettingsFragment extends PreferenceFragmentCompat {
    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
      setPreferencesFromResource(R.xml.root_preferences, rootKey);
    }
  }
}

и res/xml/root_preferences имеет:

    <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>

где массивы определены как:

 <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>

Теперь, Проблема в том, как реализовать тему, т.е. получить значения из предпочтений и реализовать. Это руководство показывает очень простой способ:

int currentNightMode = configuration.uiMode & Configuration.UI_MODE_NIGHT_MASK;
switch (currentNightMode) {
    case Configuration.UI_MODE_NIGHT_NO:
        // Night mode is not active, we're using the light theme
        break;
    case Configuration.UI_MODE_NIGHT_YES:
        // Night mode is active, we're using dark theme
        break;
}

Но вопрос в том, как мне получить значение ListPreference и установить его в uiMode.

Пожалуйста, помогите.

1 Ответ

2 голосов
/ 14 января 2020

Для сохранения темы используйте SharedPreferences ,

Для сохранения данных

//init sharedPreferences
SharedPreferences.Editor editor;
SharedPreferences sharedPreferences;
sharedPreferences = getSharedPreferences("myPref", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.apply();

//for saving String
editor.putString("theme", "day"); // here "theme" is key and "day" is value
editor.apply();

теперь вы можете получить сохраненную тему, подобную этой

//init SharedPreference here

//get SharedPreference
String sTheme = sharedPreferences.getString("theme", ""); // "theme" is key and second "" is default value

// now according to this value change theme
switch(sTheme){
    // check and set theme here
    setTheme(R.style.NightTheme);

}
// this is before setContent

setContentView(R.layout.your_activity);

Вы можете создать метод stati c, чтобы сделать все это, поскольку вы должны проверять и устанавливать тему в каждом activity

Вам также необходимо создать несколько Style в res->styles.xml

Надеюсь, это поможет!

...