不能从类型片段中对非静态方法getactivity()进行静态引用

时间:2015-01-05 09:24:54

标签: 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 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;

给出错误“无法从类型片段中对静态方法getactivity()进行静态引用”。当我将StationsFragment Fragment的Class类型更改为FragmentActivity并更改代码时如下:

  updateMapAfterUserInterection = (StationsFragment) context;

它有效。但我需要片段类。我怎么能处理这个问题?

3 个答案:

答案 0 :(得分:0)

使用以下行..

use updateMapAfterUserInterection = (UpdateMapAfterUserInterection) context;

在您需要的片段中实现UpdateMapAfterUserInterection接口。

答案 1 :(得分:0)

您可能正在UpdateMapAfterUserInterection课程中实施StationsFragment界面,然后将thisStationsFragment传递到Class对象,再转到UpdateMapAfterUserInterection

 public TouchableWrapper(Context context,StationsFragment objStationsFragment) {

    super(context);
    updateMapAfterUserInterection = 
               (UpdateMapAfterUserInterection) objStationsFragment;
}   

答案 2 :(得分:0)

要实例化TouchableWrapper,您无论如何都需要contextTouchableWrapper(Context context)对象。Fragment。如果您提供给构造函数的上下文是托管Activity的活动之一,则可以安全地将上下文转换为StationsFragment的对象,如果此活动正在实现{{1}接口