问题
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