2017-02-22 26 views
0

上午繼承稱爲ISurfaceTextureListener的接口在此代碼如何避免把我的整個代碼分爲靜態

class Camera 
{ 
    TextureView mTextureView; 
    Context _context; 
    public Camera (Context context, TextureView textureView) 
    { 
     _context = context; 
     mTextureView = textureView; 
     mTextureView.SurfaceTextureListener = new TextureViewListener(); 
    } 
    private class TextureViewListener : Java.Lang.Object, TextureView.ISurfaceTextureListener 
    { 
     public void OnSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) 
     { 
      OpenCamera(width, height); //Error Occurring Here 
     } 
    } 
    public void OpenCamera(int width, int height) 
    { 
     //Codes 
    } 
} 

錯誤:一個對象引用,需要訪問非靜態字段,方法 等

我不想讓OpenCamera()靜態,因爲我將不得不將我的整個代碼轉換爲靜態方法,那麼有沒有辦法避免它?

注意:我只能繼承接口,因爲我無法重寫對象偵聽器的「OnSurfaceTextureAvailable」方法,我發現的唯一方法是爲該對象的偵聽器分配繼承的類,它工作得很好。

+3

OpenCamera()在哪裏生活?你可以在郵件中包含該代碼嗎? –

+1

您必須創建OpenCamera所屬類的實例,然後在該對象上調用OpenCamera。 –

+1

這個錯誤很奇怪,如果你在發佈實例函數時任何非靜態成員必須已經可用,因爲當沒有顯式使用實例時假定「this」。添加更多的代碼來理解錯誤發生的原因(至少OpenCamera函數)。 – Gusman

回答

3

錯誤與您認爲的完全相反。這不是暗示你應該使OpenCamera()靜態;這意味着你試圖訪問它,就好像它是靜態的,而事實上並非如此。

你需要someObjectIhaventToldYouAnythingAbout.OpenCamera(width, height);

編輯

所以,您的評論,您的編輯,在那裏你基本上告訴我們someObjectIhaventToldYouAnythingAbout後,看來你應該這樣做:

mTextureView.SurfaceTextureListener = new TextureViewListener(this); 
} 
private class TextureViewListener : Java.Lang.Object, TextureView.ISurfaceTextureListener 
{ 
    readonly Camera camera; 

    TextureViewListener(Camera camera) 
    { 
     this.camera = camera; 
    } 

    public void OnSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) 
    { 
     camera.OpenCamera(width, height); //Error Occurring Here 
    } 
} 
public void OpenCamera(int width, int height) 
{ 
    //Codes 
} 
+0

感謝您的回覆,當我將OpenCamera()更改爲靜態時,錯誤消失了,無論如何,我添加了一些更多的代碼,它是一個類中的類是這樣搞砸了嗎?請查看代碼 –

+0

嗯,是的,當然,如果你讓OpenCamera()靜態化,那麼錯誤消失了,但這同樣說,如果你不喜歡手上的紋身,你可以切斷你的手,然後紋身不見了,但它不是一個很好的解決方案,是嗎?我修改了我的答案,告訴你應該做什麼。 –