簡體   English   中英

XML 中的 onClick 屬性鏈接到活動 class 中的方法

[英]onClick attribute in XML linking to method in Activity class

關於這個主題有很多問題,但找不到任何與我遇到的具體問題有關的問題......

在我的 layout.xml 中,我使用android:onClick標簽作為 Button 來調用右側的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'

我在 Activity 中實現了該方法,但它正在擴展Application的 class 中尋找它......我不明白為什么。 視圖和僅在活動中設置的所有內容。

如果有人需要,這里是該方法的聲明(在我的活動中,而不是在 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為 View 充氣...

正如我在編輯中提到的,使用 Activity 上下文更改getApplicationContext()可以修復它...

約定是這樣工作的:在布局 xml 文件中,你給這個屬性: android:onClick:"methodname"

然后,在 class 中,定義如下方法:

public void methodname(View v){ //你的方法代碼 }

沒有記錄任何其他這樣做的方式。 如果您需要參數,只需在該方法中調用另一個方法。

暫無
暫無

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

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