2011-09-08 50 views
0

你能檢查我的代碼是否缺少任何東西嗎?ListPreference編碼值在if語句內不執行

我想在if語句中使用listpreference中的值,但if語句從不響應存儲在listpreference中的值。

這裏的編碼我使用:

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); 
    } 

我使用的第一個敬酒的語句,以確保價值在那裏。它的值爲2,但if語句中「2」的Toast未執行。

這裏是我用於listpreference的arrays.xml:

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

這與listpreference settings.xml中:

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

所有幫助將不勝感激。

誠然, 伊馬德

回答

1

使用.equals代替== ==以來比較引用而不是實際值

if (stringChimeVolume.equals("2")) instead of 


if (stringChimeVolume== "2") 
+0

嗨Nammari,感謝您的幫助。你的代碼像夢一樣工作。 :-)真的,Emad –