Java 无法从类型片段对非静态方法getactivity()进行静态引用
我正在尝试在用户交互后重新刷新我的地图。在我的项目中有一个类:Java 无法从类型片段对非静态方法getactivity()进行静态引用,java,android,android-fragments,static,android-context,Java,Android,Android Fragments,Static,Android Context,我正在尝试在用户交互后重新刷新我的地图。在我的项目中有一个类: public class TouchableWrapper extends FrameLayout { private long lastTouched = 0; private static final long SCROLL_TIME = 200L; private UpdateMapAfterUserInterection updateMapAfterUserInterection; public TouchableWr
public class TouchableWrapper extends FrameLayout {
private long lastTouched = 0;
private static final long SCROLL_TIME = 200L;
private UpdateMapAfterUserInterection updateMapAfterUserInterection;
public TouchableWrapper(Context context) {
super(context);
// Force the host activity to implement the UpdateMapAfterUserInterection Interface
try {
updateMapAfterUserInterection = (StationsFragment.getActivity()) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement UpdateMapAfterUserInterection");
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
lastTouched = SystemClock.uptimeMillis();
break;
case MotionEvent.ACTION_UP:
final long now = SystemClock.uptimeMillis();
if (now - lastTouched > SCROLL_TIME) {
// Update the map
updateMapAfterUserInterection.onUpdateMapAfterUserInterection();
}
break;
}
return super.dispatchTouchEvent(ev);
}
// Map Activity must implement this interface
public interface UpdateMapAfterUserInterection {
public void onUpdateMapAfterUserInterection();
}
}
我的StationsFragment类包含并刷新地图。但是在这一行的TouchableWrapper类中
updateMapAfterUserInterection = (StationsFragment.getActivity()) context;
给出一个错误“无法从类型fragment中对非静态方法getactivity()进行静态引用”。当我将StationFragment fragment的类类型更改为FragmentActivity并按如下方式更改代码时:
updateMapAfterUserInterection = (StationsFragment) context;
它可以工作。但我需要Fragment类。我如何处理这个问题?使用下面的行
use updateMapAfterUserInterection = (UpdateMapAfterUserInterection) context;
在所需片段中实现
updateMapAfterUserInterction
接口 您可能正在StationFragment
类中实现UpdateMapAfterUserInterection
接口,然后将此从StationFragment
传递给类对象,以UpdateMapAfterUserInterection
,如下所示:
public TouchableWrapper(Context context,StationsFragment objStationsFragment) {
super(context);
updateMapAfterUserInterection =
(UpdateMapAfterUserInterection) objStationsFragment;
}
要实例化您的TouchableWrapper
,由于TouchableWrapper(context context)
,您在任何情况下都需要一个context
对象。如果提供给构造函数的上下文是承载片段的活动之一,则可以安全地将上下文强制转换到活动的对象,如果此活动正在实现StationsFragment
接口,请回答。但是TouchableWrapper类不是一个活动。因此GetActivity是无用的。很抱歉,最初没有阅读您的代码,并给出了您最后几行问题的答案。。检查更新的答案