鍍金池/ 問(wèn)答/Java  Android  Office/ 為什么一定要申明接收View?

為什么一定要申明接收View?

新手最近在學(xué)android,今天搞了個(gè)小問(wèn)題搞了TM一下午!我新建個(gè)4.0的項(xiàng)目
我寫了個(gè)按鈕

<Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="計(jì)算"
            android:onClick="btnDivideClick"/>

然后運(yùn)行到模擬器點(diǎn)擊按鈕一直報(bào) Unfortunately,xxx has stopped!, 然后就是各種找問(wèn)題,但是沒找到哪里寫錯(cuò)了,然后就刪除各種不相關(guān)的代碼 最后就特么剩下上面按鈕 和下面方法

public void btnDivideClick(){
        //EditText edit_1 = (EditText)findViewById(R.id.etFirst);
        //EditText edit_2 = (EditText)findViewById(R.id.etSecond);
        //TextView textview = (TextView)findViewById(R.id.tvResult);

        //String str_1 = edit_1.getText().toString();
        //String str_2 = edit_2.getText().toString();

        //textview.setText(str_1 + str_2);
    }

方法的代碼也注釋了 還tm報(bào)錯(cuò), 瞬間崩潰了,后來(lái)發(fā)現(xiàn) 方法里定義(View view)就沒事了,我草啊.... 我代碼里又沒用到這個(gè)參數(shù),為何要定義?我之前沒定義我不見報(bào)這個(gè)錯(cuò)???

回答
編輯回答
深記你

Java 要求方法定義的形參必須和實(shí)參一致。
Android 通過(guò)分析 XML ,能夠自動(dòng)將組件的點(diǎn)擊事件綁定到你設(shè)置的方法上,并且通過(guò)帶入 View 對(duì)象作為實(shí)參的形式進(jìn)行調(diào)用。
而如果你方法定義的形參并不是 View ,那就會(huì)違背 Java 的調(diào)用邏輯,產(chǎn)生異常。

2017年7月25日 18:16
編輯回答
懷中人
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/button_send"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_send"
    android:onClick="sendMessage" />
/** Called when the user touches the button */
public void sendMessage(View view) {
    // Do something in response to button click
}

The method you declare in the android:onClick attribute must have a signature exactly as shown above. Specifically, the method must:

  • Be public
  • Return void
  • Define a View as its only parameter (this will be the View that was clicked)

android教程:Responding to Click Events

2018年2月6日 13:19