0
在偏好設置中,我想根據單位類型(Imprial或Metric)更改偏好視圖。在創建方法中,我檢查首選項的最後一個值是什麼,但總是在應用程序啓動時返回度量標準。 我也有一個OnSharedPreferenceChangeListener
,我正在改變視圖根據用戶輸入,這是工作。如何在調用onCreate時獲得保存的偏好?在Java需要如何檢索共享首選項onCreate?
public class PrefMainActivity extends PreferenceActivity{
String TAG="BlueGlucose";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(R.string.action_settings);
this.init_view();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
SharedPreferences.OnSharedPreferenceChangeListener spChanged = new
SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
PrefMainActivity.this.init_view();
}
// your stuff here
};
private void init_view(){
try
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String metric = getResources().getString(R.string.imperial);
if (prefs.getString("measurement_unit",metric) == metric)
getFragmentManager().beginTransaction().replace(android.R.id.content,
new PrefMainFragmentImperial()).commit();
else
getFragmentManager().beginTransaction().replace(android.R.id.content,
new PrefMainFragmentMetric()).commit();
prefs.registerOnSharedPreferenceChangeListener(spChanged);
}
catch(Exception ex)
{
}
}