How to use an AndroidAnnotations SharedPref with a PreferenceActivity?

我的梦境 提交于 2020-01-15 03:56:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!