2012-05-23 47 views
1

我有問題了解共享首選項。我有活動,用戶將在其中插入密碼,開始價格,等待價格等。我的計劃是設置初始值,並且如果用戶願意,用戶會更改該值。 我的問題是:如果我在onCreate()方法中創建首選項,那麼每次運行應用程序時應如何應用更改(使用SharedPreferences.Editor),它應該在首選項中創建新值。編輯SharedPreferences值?

回答

1

爲了獲得共享偏好,用下面的方法在您的活動:

SharedPreferences prefs = this.getSharedPreferences(
      "com.example.app", Context.MODE_PRIVATE); 

要閱讀偏好:

String dateTimeKey = "com.example.app.datetime"; 

// use a default value using new Date() 
long l = prefs.getLong(dateTimeKey, new Date().getTime()); 

編輯和保存喜好

Date dt = getSomeDate(); 
    prefs.edit().putLong(dateTimeKey, dt.getTime()).commit();