android:onClick attribute

本文详细介绍了如何在XML文件中配置Button组件,并在Activity类中实现对应的点击事件处理方法。强调了方法签名的规范,包括方法的访问权限、返回类型及参数设置,以确保点击事件能够正确触发。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文以Button为例进行介绍

1》XML文件代码如下:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_send"
    android:onClick="sendMessage" />

The android:onClick attribute’s value, "sendMessage", is the name of a method in your activity that the system calls when the user clicks the button.

2》Open the Activity class (located in the project'ssrc/ directory) and add the corresponding method:

/** Called when the user clicks the Send button */
public void sendMessage(View view) {
    // Do something in response to button
}


注意:

In order for the system to match this method to the method name given to android:onClick, the signature must be exactly as shown. Specifically, the method must:(该方法必须全部满足以下三个条件:)
•Be public.(public)
•Have a void return value.(返回值为void)
•Have a View as the only parameter (this will be the View that was clicked).(ps:有且仅有一个参数类型为View的参数,这一点特别重要,否则点击该按钮时,不会调用该方法。)


这也是有时候明明指定了android:onClick属性,并且Activity中也实现了对应的方法,但是实际执行的时候就是没有执行指定的方法的原因。仔细看一下你的方法是否同时满足以上三个条件!!!



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值