2011-02-24 20 views
0

在黑暗中摸索......這一次,我在Eclipse中收到以下錯誤:在類型<type>方法調用(活動)並不適用於參數(新View.OnClickListener(){})

在類型 IntentsUtils方法調用(活性)是不適用的 參數(新 View.OnClickListener(){})

此錯誤指的是呼叫()行中的回調連接到一個按鈕,在擴展活動類:

public class UnderstandingIntents extends Activity { 
    ... 
    ... 
    ... 
    // A call-back for when the user presses the testintents button. 
    OnClickListener mTestIntentsListener = new OnClickListener() { 
     public void onClick(View v) { 
     IntentsUtils.call(this); 
     } 
    }; 
} 

IntentsUtils是從listing 3-33 here逐字複製的類。

這個錯誤是什麼意思?

回答

5

這裏的問題是,你正試圖在一個匿名內部類參考Activity類(UnderstandingIntents),因此,當你說「這個」,它指的是View.OnClickListener (){}

糾正這種做下面的代碼:

IntentsUtils.call(UnderstandingIntents.this); 

這樣,你的Activity類被引用。

+1

這正是我所說的來自C++的陡峭學習曲線。這不僅僅是Android API,術語和新概念。這就像「匿名內心階層」,我不知道(直到現在)。所有答案基本相同,但你的教育程度最高。 ++ 1。謝謝! – 2011-02-24 18:34:55

+1

對於像我這樣的新一代無知的新手,這裏是「匿名內部類」的介紹(不是「內部類」暗示匿名嗎?)http://www.roseindia.net/javatutorials/anonymous_innerclassestutorial.shtml – 2011-02-24 19:47:10

+2

好文章!要回答你的問題,內部類不一定意味着它是匿名的。它對包含在外部類(Java文件)之外的類是匿名的。通過語法,匿名內部類不使用關鍵字類,實現或擴展(如您的問題所示)。它的本質就是這樣一個類,它只是在一個方法中創建的。然而,Inner類使用這些關鍵字來創建一個獨立於某個方法的類。一個很好的例子可以在這裏找到:http://download.oracle.com/javase/tutorial/java/javaOO/innerclasses.html – 2011-02-24 20:02:19

1

嘗試這種

IntentsUtils.call(UnderstandingIntents.this); 
2

送入IntentsUtils.call()this參數是指內正在使用它的對象,在這種情況下OnClickListener一個實例。嘗試用UnderstandingIntents.this更換this參數:

IntentsUtils.call(UnderstandingIntents.this); 
相關問題