所以基本上,我有一个需要 Context
的方法为了执行多项任务。
public void openDatePicker() { Context c; }
我想知道,如何定义方法调用者的上下文,这样我就不必每次调用方法时都将其作为参数插入。
最佳答案
让我们对有一个基本的了解上下文 .
上下文 允许访问特定于应用程序的资源和类,以及调用应用程序级操作,例如启动 Activity 、广播和接收 Intent 等。
一个 上下文 代表你的环境。它代表您在系统中所处的状态。
一个 安卓应用程序有 Activity 。 上下文 就像您的应用程序当前运行的环境的句柄。 Activity 对象继承 上下文 目的。
那么,如何访问上下文 在您的应用程序中?
示例:查看 . 获取上下文 () 返回 上下文 View 当前正在运行。通常是当前 Activity 的Activity。
View mView = this.getLayoutInflater().inflate(R.layout.myLayout, myViewGroup);
或者,
Intent mIntent = new Intent(this, MyActivity.class);
this.startActivity(mIntent);
示例:绑定(bind)应用程序范围的类。
Intent mIntent = new Intent(this, MyPersistent.class);
MyServiceConnection mServiceConnection = new MyServiceConnection();
if (mServiceConnection != null) {
getApplicationContext().bindService(mIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
}
ContextWrapper 是“ 上下文 的代理实现,它只是将其所有调用委托(delegate)给另一个 上下文 。可以在不更改原始 上下文 的情况下修改行为。” (根据javadocs)..
现在,可能会出现一个问题!如何访问 上下文 不扩展 Activity 的类中的对象?因此,可以通过以下方式实现:
例子:
public class MyActivity extends Activity {
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getApplicationContext();
new Helper(context);
}
}
public class Helper {
Context mContext;
Helper(Context ctx){
this.mContext= ctx;
}
//Now you can use this mContext anywhere in your class.
}
最后,获得 上下文 在您的应用程序中的任何地方,您都可以在您的应用程序中定义一个新类:
public class MyContext extends Application {
private static MyContext instance;
@Override
public void onCreate() {
instance = this;
super.onCreate();
}
public static Context getContext(){
return instance;
// or return instance.getApplicationContext();
}
}
在您的 list 中,您需要将此类添加到“应用程序”选项卡中的“名称”字段中,如下所示:
<application
android:name="com.example.app.MyContext "
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
.......
<activity
......
</activity>
获取 上下文 在您的应用程序中的任何位置,即在您项目的任何类中,您都可以调用此类的函数,如下所示:
MyContext.getContext();
此函数将返回 上下文 可以用来执行任务。
所以,来回答你的问题。我猜最后两种方法可以解决您的问题,即通过 上下文 对象到类并定义一个扩展应用程序的新类。
这就是@Achmad Naufal Syafiq。这是我帮助你的最大努力。
关于android - 调用不同类中的方法时如何获取上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45135697/