为什么一定要申明接收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!, 然后就是各种找问题,但是没找到哪里写错了,然后就删除各种不相关的代码 最后就特么剩下上面按钮 和下面方法

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报错, 瞬间崩溃了,后来发现 方法里定义(View view)就没事了,我草啊.... 我代码里又没用到这个参数,为何要定义?我之前没定义我不见报这个错啊?

阅读 2.1k
2 个回答

Java 要求方法定义的形参必须和实参一致。
Android 通过分析 XML ,能够自动将组件的点击事件绑定到你设置的方法上,并且通过带入 View 对象作为实参的形式进行调用。
而如果你方法定义的形参并不是 View ,那就会违背 Java 的调用逻辑,产生异常。

<?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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题