ElencoPreference Coding Value non eseguendo l'istruzione IF
-
28-10-2019 - |
Domanda
Puoi controllare il mio codice per qualcosa di mancante?
Sto cercando di ottenere il valore da un ListPreference in un'istruzione IF, ma l'istruzione IF non risponde mai al valore memorizzato nella referenza di List.
Qui la codifica che sto usando:
String stringChimeVolume = clockSettings.getString("ChimeVolume",
"Default");
Toast.makeText(context, "The preference is: " + stringChimeVolume,
Toast.LENGTH_SHORT).show();
if (stringChimeVolume == "2") {
manager.setStreamVolume(AudioManager.STREAM_MUSIC,
2, AudioManager.FLAG_VIBRATE);
Toast.makeText(context, "The volume is at 2: ",
Toast.LENGTH_SHORT).show();
} else if (stringChimeVolume == "3") {
Toast.makeText(context, "The volume is at 3: ",
Toast.LENGTH_SHORT).show();
manager.setStreamVolume(AudioManager.STREAM_MUSIC,
7, AudioManager.FLAG_VIBRATE);
}
else if (stringChimeVolume == "4") {
manager.setStreamVolume(AudioManager.STREAM_MUSIC,
15, AudioManager.FLAG_VIBRATE);
}
Ho usato la prima istruzione toast per garantire che fosse presente un valore. Ha il valore di 2 ma il brindisi nell'istruzione IF per "2" non è in esecuzione.
Ecco gli arrays.xml che ho usato per ListPreference:
<string-array name="chimeVolumeLabels">
<item>Use System Volume</item>
<item>Emad</item>
<item>Medium</item>
<item>Loud</item>
</string-array>
<string-array name="chimeVolumeValues">
<item>1</item>
<item>2</item>
<item>3</item>
<item>4</item>
</string-array>
Questa è impostazione.xml con ListPreference:
<PreferenceCategory android:title="Media:">
<CheckBoxPreference android:key="ChimeWhenMusicIsPlaying"
android:title="@string/ChimeWhenMusicIsPlayingTitle" android:summary="@string/ChimeWhenMusicIsPlayingSummary"
android:defaultValue="false" />
<ListPreference android:title="Chime Volume"
android:key="ChimeVolume" android:summary="Select volume for the chiming sound."
android:entries="@array/chimeVolumeLabels" android:entryValues="@array/chimeVolumeValues"
android:defaultValue="1" />
</PreferenceCategory>
Tutto l'aiuto sarà molto apprezzato.
Davvero, Emad
Soluzione
usa .equals invece di == poiché == confronta i riferimenti non il valore effettivo
piace
if (stringChimeVolume.equals( "2")) instead of
if (stringChimeVolume== "2")
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow