android development_为<button>注册onClick事件

通过button标签中的android:onClick属性设置click响应方法:以打开百度为例

xml中注册的button标签注册点击onClick属性对应点击触发的方法

<Button
android:id="@+id/button2"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:onClick="testClick"
android:text="@string/test_click" />

在kotlin中实现testClick方法(以其中反馈一个Toast为例并打开百度)

/** Called when the user touches the button
on need to modify parameter of the method decalared in <Button> tag*/
fun testClick(view: View) {
Toast.makeText(this, "test the method testClick", Toast.LENGTH_SHORT).show()
val intent = Intent(Intent.ACTION_VIEW).apply {
data = Uri.parse("https://www.baidu.com")
}
startActivity(intent)
// Do something in response to button click
}

执行顺序

您可以设计好ui(不必在此时设计监听事件,您可以在之后设计好监听函数后返回到UI设计做相应的注册修改即可(这时候,您可以从列表中直接看到您已经声明/设计在kt文件中的对应行为函数)
在这里插入图片描述

在这里插入图片描述

posted @   xuchaoxin1375  阅读(4)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
点击右上角即可分享
微信分享提示