How do I get the context from within an activity class?

孤者浪人 提交于 2020-12-12 07:37:47

问题


While I'm trying to initialize context using getActivity(), Android Studio shows an error "could not resolve symbol". How do I get the context from within an activity class?


回答1:


Don't use getActivity. Use this.

For example:

Context context = this;

getActivity() is used if you are inside fragment. In an activity, you can get by using the this keyword.

By the way, inside an activity, you don't need to use context, getSharedPreferences() method is already present in Activity. Simply call getSharedPreferences() method without context reference.




回答2:


private void saveScore() {
    Context context = FullscreenActivity.this;
    SharedPreferences sharedPref = context.getSharedPreferences(getString(R.string.preference_file_key),  Context.MODE_PRIVATE);
}


来源:https://stackoverflow.com/questions/39503168/how-do-i-get-the-context-from-within-an-activity-class

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