在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

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

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

新手最近在學android,今天搞了個小問題搞了TM一下午!我新建個4.0的項目
我寫了個按鈕

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

然后運行到模擬器點擊按鈕一直報 Unfortunately,xxx has stopped!, 然后就是各種找問題,但是沒找到哪里寫錯了,然后就刪除各種不相關(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報錯, 瞬間崩潰了,后來發(fā)現(xiàn) 方法里定義(View view)就沒事了,我草啊.... 我代碼里又沒用到這個參數(shù),為何要定義?我之前沒定義我不見報這個錯???

回答
編輯回答
深記你

Java 要求方法定義的形參必須和實參一致。
Android 通過分析 XML ,能夠自動將組件的點擊事件綁定到你設(shè)置的方法上,并且通過帶入 View 對象作為實參的形式進行調(diào)用。
而如果你方法定義的形參并不是 View ,那就會違背 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