RoboGuice 注入不同的 SharedPreferences
RoboGuice inject different SharedPreferences
在RoboGuice
我使用的时候:
@Inject
SharedPreferences prefs;
它注入默认 SharedPreferences
如何注入 非默认 首选项?
喜欢 context.getSharedPreferences("my_prefs", Context.MODE_PRIVATE)
来自 Roboguice
文档:
Shared Preferences
Class: SharedPreferences
Provider: SharedPreferencesProvider
Scope: Transient Injection
Points: Constructors, Fields, Methods By default
roboguice will retrieve an instance of Android SharedPreferences using
the filename: "default". This is not the default file name android
uses for your shared preferences. If you would like to override the
file name then you can set up a binding when RoboGuice is initialized.
Android Default Shared Preferences File Name Binding
bindConstant()
.annotatedWith(SharedPreferencesName.class)
.to("com.mypackage.myapp_preferences");
Example
public class MyActivity extends RoboActivity {
@Inject SharedPreferences sharedPreferences;
}
Provider Example
public class MyActivity extends RoboActivity {
@Inject Provider<SharedPreferences> sharedPreferencesrProvider;
}
From: https://github.com/roboguice/roboguice/wiki/Provided-Injections
我以前没用过RoboGuice
,但我很确定:
@Inject
SharedPreferences prefs;
等同于:
SharedPreferences prefs = getActivity().getPreferences(Context.MODE_PRIVATE);
所以如果你想得到一个键值,你只能使用:
int highScore = prefs.getInt("my_prefs", defaultValue);
并输入一个新值:
editor.putInt("my_prefs", newHighScore);
希望对您有所帮助
在RoboGuice
我使用的时候:
@Inject
SharedPreferences prefs;
它注入默认 SharedPreferences
如何注入 非默认 首选项?
喜欢 context.getSharedPreferences("my_prefs", Context.MODE_PRIVATE)
来自 Roboguice
文档:
Shared Preferences
Class: SharedPreferences
Provider: SharedPreferencesProvider
Scope: Transient Injection
Points: Constructors, Fields, Methods By default
roboguice will retrieve an instance of Android SharedPreferences using the filename: "default". This is not the default file name android uses for your shared preferences. If you would like to override the file name then you can set up a binding when RoboGuice is initialized.
Android Default Shared Preferences File Name Binding
bindConstant() .annotatedWith(SharedPreferencesName.class) .to("com.mypackage.myapp_preferences");
Example
public class MyActivity extends RoboActivity { @Inject SharedPreferences sharedPreferences; }
Provider Example
public class MyActivity extends RoboActivity { @Inject Provider<SharedPreferences> sharedPreferencesrProvider; }
From: https://github.com/roboguice/roboguice/wiki/Provided-Injections
我以前没用过RoboGuice
,但我很确定:
@Inject
SharedPreferences prefs;
等同于:
SharedPreferences prefs = getActivity().getPreferences(Context.MODE_PRIVATE);
所以如果你想得到一个键值,你只能使用:
int highScore = prefs.getInt("my_prefs", defaultValue);
并输入一个新值:
editor.putInt("my_prefs", newHighScore);
希望对您有所帮助