问题
I have a PreferenceActivity that I'd like to use with AndroidAnnotations @SharedPref, so the PreferenceActivity would use the data in the @SharedPref.
Is there a good way to do this? How do I tell the activity to to use @SharedPref I created elsewhere? Is there a good way to do this without setting the value of each preference?
Here is the activity code I'm currently using:
public class SettingsActivity extends PreferenceActivity {
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
回答1:
A PreferenceActivity is an Activity, so you just need to annotate it with @EActivity to start using the annotations, such as @SharedPref.
If you want to share preferences between activities, AndroidAnnotations has the notion of scope, as defined here.
You should use the Scope.UNIQUE scope to share it between all activities.
SharedPref were thought as a way to easily store data into SharedPreferences. Not necessarily to be used with PreferenceActivity.
You can use getSharedPreferences() to access the shared preferences instance, you can't use that to define the preference to use in the activity. So it's mainly a matter of using the right Android APIs.
@EActivity
public class SettingsActivity extends PreferenceActivity {
@Pref
MyPrefs_ myPrefs;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
getPreferenceManager().setSharedPreferencesName("MyPrefs");
addPreferencesFromResource(R.xml.preferences);
}
}
来源:https://stackoverflow.com/questions/10970068/how-to-use-an-androidannotations-sharedpref-with-a-preferenceactivity