2015-08-18 146 views

回答

1

preference.xml:

<SwitchPreference 
    android:key="test" 
    android:title="Test" /> 

PreferenceActivity:

public class TestPrefActivity extends PreferenceActivity { 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     addPreferencesFromResource(R.xml.sample); 
    } 
} 

註冊共享偏好對象的變化

SharedPreferences sharedPrefs = PreferenceManager 
      .getDefaultSharedPreferences(MainActivity.this); 
    sharedPrefs.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() { 
     @Override 
     public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { 
      boolean test = sharedPreferences.getBoolean("test", false); 
      Log.e(TAG, "Value:" + test); 
     } 
    }); 
+0

R.string.SWITCH是什麼意思?我應該創建一個字符串嗎? – Blacklotis

+0

這是給你的偏好的名字 – Prasad

+0

'android:key =「pref_sync」'在你的xml中給出 – Prasad