D
D
Danil Ochagov2018-07-17 12:50:35
Java
Danil Ochagov, 2018-07-17 12:50:35

The code to disable sound through the settings does not work?

I am making an application and it is necessary that in the settings you can remove the sound, I save the data through sharedPreferences, but the switch does not save the position (checked, nonchecked) and the sound still goes on. Here is the code from SettingsActivity in the onCreate() method:

cb_sound_settings = findViewById(R.id.cb_settings_sounds);
  if (cb_sound_settings.isChecked()) {
        sharedPreferences = getSharedPreferences("MyPref", MODE_PRIVATE);
        editor = sharedPreferences.edit();
        editor.putBoolean("Sounds", true);
        editor.apply();
    } else {
        sharedPreferences = getSharedPreferences("MyPref", MODE_PRIVATE);
        editor = sharedPreferences.edit();
        editor.putBoolean("Sounds", false);
        editor.apply();
    }

    sharedPreferences = getSharedPreferences("MyPref", MODE_PRIVATE);
    if (sharedPreferences.getBoolean("Sounds", true)) {
        cb_sound_settings.setChecked(true);
    } else {
        cb_sound_settings.setChecked(false);
   }

Xml code from layout_settings.xml:
<Switch
    android:id="@+id/cb_settings_sounds"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="5dp"
    android:background="@color/colorGray"
    android:checked="true"
    android:padding="15dp"
    android:text="@string/settings_sounds"
    android:textColor="@color/colorBlack"
    android:textSize="18sp" />

And the code from MainActivity, where there should have been a sound ban:
public void showSuccessfulToastVerb () {
    Toast.makeText(MainActivity.this, "It's not a irregular verb", Toast.LENGTH_SHORT).show();
    successfulSound = MediaPlayer.create(this, R.raw.successful);
    sharedPreferences = getSharedPreferences("MyPref", MODE_PRIVATE);
    if (sharedPreferences.getBoolean("Sounds", true)) {
        successfulSound.start();
    }
}

Please help, the same garbage was when I tried to ban animation (

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2018-07-17
@danilochagov

Because you're not reacting to a state change. OnCheckedChangeListener or something like that.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question