当我尝试使用getActivity()
初始化context
时,Android Studio显示错误“无法解析符号”。在活动类中如何获取上下文?
当我尝试使用getActivity()
初始化context
时,Android Studio显示错误“无法解析符号”。在活动类中如何获取上下文?
getActivity
,而应该使用 this
。Context context = this;
getActivity()
方法在片段中使用。在活动中,可以使用this
关键字获取。
顺便说一句,在活动中,您不需要使用context
,因为getSharedPreferences()
方法已经存在于Activity
中。只需调用getSharedPreferences()
方法而无需context
引用即可。
private void saveScore() {
Context context = FullscreenActivity.this;
SharedPreferences sharedPref = context.getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
}