[英]How to call a method of the MapActivity from another activity in Android?
I am working on an Android application that based on Google Maps API. 我正在使用基于Google Maps API的Android应用程序。 I have a
refresh()
method to refresh my MapActivity
. 我有一个
refresh()
方法来刷新MapActivity
。 I want to call the refresh()
method to refresh the map after I managed my POIs from another activity. 在我从其他活动管理POI后,我想调用
refresh()
方法刷新地图。
MapActivity.refresh();
This is my refresh()
method: 这是我的
refresh()
方法:
public void refresh() {
Intent intent = getIntent();
finish();
startActivity(intent);
}
I know I can call this method from other activities if it is static
. 我知道如果它是
static
我可以从其他活动中调用此方法。 So, I made this following change: 因此,我进行了以下更改:
public static void refresh() {
Intent intent = getIntent();
finish();
startActivity(intent);
}
After that, I get this message: 之后,我收到此消息:
Non-static method 'getIntent()' cannot be referenced from a static context
Is there another way to refresh the map? 还有另一种刷新地图的方法吗?
After I read the useful comments, I made this mapReset()
method: 阅读有用的注释后,我做了以下
mapReset()
方法:
public void mapReset() {
map.clear();
addAllMarkers();
//...
}
I add this method into the ChildEventListener
and the map will be reset after I managed the POIs. 我将此方法添加到
ChildEventListener
并且在管理POI之后将重置地图。 This solves my problem. 这解决了我的问题。
poiFirebase.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//...
mapReset();
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
//...
mapReset();
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
//...
mapReset();
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
//...
mapReset();
}
@Override
public void onCancelled(FirebaseError firebaseError) {
//...
}
});
A static method is defined once , and is not related to a class instance. 静态方法只定义一次 ,并且与类实例无关。 So you can't modify a class instance with it.
因此,您无法使用它修改类实例。 What you could do is store your
MapActivity
in a class as a static member, for example: 您可以做的是将
MapActivity
作为静态成员存储在类中,例如:
public class World {
public static MapActivity myMap;
...
}
Then you can access your map like this: 然后,您可以像这样访问地图:
World.myMap.refresh();
The difference being that your whole MapActivity is considered a static member, but once you called World.myMap
, you have a class instance. 区别在于您将整个MapActivity视为静态成员,但是一旦调用
World.myMap
,便有了一个类实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.