[英]Android: How to pass Activity from MainActivity to a separate non-Activity class
I am writing an Android application in which I am accessing a shared resource, implemented through extending the Application class to a public class (shared resource).我正在编写一个 Android 应用程序,其中我正在访问共享资源,通过将应用程序 class 扩展到公共 class(共享资源)来实现。 Below is the code containing my shared resource ( ScheduleStorage.java ):
下面是包含我的共享资源的代码( ScheduleStorage.java ):
import android.app.Application;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ScheduleStorage extends Application {
private Map<String, Match> schedule = new HashMap<String, Match>();
// Getter
public Map<String, Match> getSchedule() {
return schedule;
}
// Setter
public void setSchedule(Map<String, Match> newSchedule) {
this.schedule = newSchedule;
}
}
The following line of code accesses the schedule property of ScheduleStorage
:以下代码行访问
ScheduleStorage
的 schedule 属性:
fun getSchedule(): Map<String, Match> {
return (getApplication() as ScheduleStorage).schedule
}
As you can see, in order to access the ScheduleStorage resource, I need to get the application first.如您所见,为了访问 ScheduleStorage 资源,我需要先获取应用程序。 However, when I am passing the Context into another class, when I execute the following line of code:
但是,当我将上下文传递到另一个 class 时,当我执行以下代码行时:
ScheduleStorage scheduleStorage = context.getApplication().getSchedule();
Cannot resolve method getApplication()
无法解析方法 getApplication()
How do I get the Activity in a non-Activity class?如何在非活动 class 中获得活动?
You have to cast view's context to activity which the view is running in您必须将视图的上下文转换为视图正在运行的活动
((Activity's name which pass to constructor of view)
getContext()).getApplication().getSchedule();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.