我正在尝试在用户交互后重新调整我的地图。在我的项目中,有一个类是这样的:
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();
}
}
我的站片段类包含并刷新地图。但是在这一行的 TouchableWrapper 类中
updateMapAfterUserInterection = (StationsFragment.getActivity()) context;
给出错误"无法从类型片段中对非静态方法 getactivity() 进行静态引用"。当我将 StationsFragment Fragment 的类类型更改为 FragmentActivity 并像这样更改代码时:
updateMapAfterUserInterection = (StationsFragment) context;
它有效。但是我需要片段类。如何处理这个问题?
可能您正在StationsFragment
类中实现UpdateMapAfterUserInterection
接口,然后将this
从StationsFragment
传递到类对象,UpdateMapAfterUserInterection
为:
public TouchableWrapper(Context context,StationsFragment objStationsFragment) {
super(context);
updateMapAfterUserInterection =
(UpdateMapAfterUserInterection) objStationsFragment;
}
要实例化您的TouchableWrapper
,无论如何您都需要一个context
对象,由于TouchableWrapper(Context context)
。如果您提供给构造函数的上下文是承载Fragment
的活动之一,则可以安全地将上下文强制转换为Activity
的对象(如果此活动正在实现该StationsFragment
接口
使用以下行。
use updateMapAfterUserInterection = (UpdateMapAfterUserInterection) context;
在所需的片段中实现UpdateMapAfterUserInterection
接口。