如何从活动类中获取上下文? [英] How do I get the context from within an activity class?
问题描述
当我尝试使用 getActivity()
初始化 context
时,Android Studio显示错误无法解析符号".如何从活动类中获取上下文?
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?
推荐答案
请勿使用 getActivity
.使用 this
.
例如:
Context context = this;
如果在片段中,请使用
getActivity()
.在一个活动中,您可以使用 this
关键字来获得.
getActivity()
is used if you are inside fragment. In an activity, you can get by using the this
keyword.
顺便说一句,在活动内部,您不需要使用 context
, Activity
中已经存在 getSharedPreferences()
方法.只需调用没有 context
引用的 getSharedPreferences()
方法即可.
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.
这篇关于如何从活动类中获取上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!