簡體   English   中英

無法從類型片段中靜態引用非靜態方法getactivity()

[英]cannot make a static reference to the non-static method getactivity() from the type fragment

我試圖在用戶交互后刷新地圖。在我的項目中,有一個這樣的類:

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;

它可以工作,但是我需要Fragment Class。如何處理這個問題?

使用下面的行..

use updateMapAfterUserInterection = (UpdateMapAfterUserInterection) context;

在所需的片段中實現UpdateMapAfterUserInterection接口。

可能您正在StationsFragment類中實現UpdateMapAfterUserInterection接口,然后將thisStationsFragment傳遞給Class對象,並傳遞給UpdateMapAfterUserInterection如下所示:

 public TouchableWrapper(Context context,StationsFragment objStationsFragment) {

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

要實例化您的TouchableWrapper ,由於TouchableWrapper(Context context) ,無論如何都需要一個context對象。 如果提供給構造函數的上下文是承載Fragment的活動之一,則可以安全地將上下文強制轉換為Activity的對象,前提是該活動正在實現StationsFragment接口

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM