2011-07-06 29 views
1

關於這個問題有很多問題,但找不到任何具體問題,我有...onClick屬性在XML鏈接到Activity類中的方法

在我的layout.xml中,我使用標籤爲一個按鈕調用正確的onClickListener。我得到的錯誤:

java.lang.IllegalStateException: Could not find a method handle_cancel(View) in the activity class com.matthieu.HelloWorldApplication for onClick handler on view class android.widget.Button with id 'button_cancel' 

我在工作中使用的這種方法,但在擴展Application類尋找它。我不明白爲什麼。視圖和所有僅在「活動」中設置的內容。

如果有人需要,這裏是方法的聲明(在我的活動,而不是在HelloWorldApplication):

public void handle_cancel(View v) { 
    // do something useful here 
} 

編輯(從adamp要求)......,可能回答我的問題:

這裏是第一個使用該佈局的部分代碼...

public class AddVocabularyActivity extends Activity 
{ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     setContentView(R.layout.top); // that layout contains an empty LinearLayout id/main_content 
    } 

    private some_other_function() { 
     LinearLayout main_content = (LinearLayout) findViewById(R.id.main_content); 
     main_content.removeAllViews(); 
     View.inflate(getApplicationContext(), R.layout.hello, main_content); // layout.hello is the one containing the button 
    } 

    // some other stuff 
} 

雖然複製/粘貼此代碼,我猜ŧ他的問題是,我以前getApplicationContext膨脹與Button查看...

+0

您可以將代碼發佈到何處使用該佈局? – adamp

回答

3

正如我在編輯提到,隨着活動範圍內修復它改變getApplicationContext() ...

0

的約定是這樣的: 在佈局xml文件,你把這個屬性: 安卓的onClick:「方法名」

然後,在類中,可以定義這樣的方法:

公共無效的方法名(視圖v){ //你的我thod code }

這樣做的其他方式沒有記錄。如果你需要參數,只需在該方法內調用另一個方法即可。

+1

我正確地做了所有這些。問題在於你應該在哪個類中定義該方法。特別是當您使用視圖充氣器使用該佈局時。 – Matthieu

+0

問題是,這只是一個幫手,如果這不適合,你需要做的只是通常的Button按鈕=(Button)findViewByID(R.id.yourbutton);然後是聽衆等 – AlfredoVR

相關問題