首页 技术 正文
技术 2022年11月15日
0 收藏 636 点赞 4,184 浏览 1759 个字

按钮findViewBuId

    <Button
android:id="@+id/mButton4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="跳转"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@+id/mButton3" />

XML 没有变化

val button4 = findViewById<Button>(R.id.mButton4)

点击事件有三种写法

1.匿名内部类

button4.setOnClickListener {
Toast.makeText(this, "java", Toast.LENGTH_LONG).show()
}

这里就使用Toast打印一句话,Toast的写法和java中的写法一样

2.Activity实现全局OnClickListener接口

class MainActivity : AppCompatActivity(), View.OnClickListener {    override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main) initView()
}

在 AppCompatActivity类后加上 View.OnClickListener 用“,”分割,这种方法与java的区别是没有implements关键字表示实现接口。

private fun initView() {
val button1 = findViewById<Button>(R.id.mButton1)
val button2 = findViewById<Button>(R.id.mButton2)
val button4 = findViewById<Button>(R.id.mButton4)
val button5 = findViewById<Button>(R.id.mButton5)
val button6 = findViewById<Button>(R.id.mButton6)
val button7 = findViewById<Button>(R.id.mButton7) button1.setOnClickListener(this)
button2.setOnClickListener(this)
button7.setOnClickListener(this)
override fun onClick(v: View?) {
when (v?.id) {
R.id.mButton1 ->
Toast.makeText(this, "java", Toast.LENGTH_LONG).show()
R.id.mButton2 ->
Toast.makeText(this, "java", Toast.LENGTH_LONG).show()
}
}

在kotlin中使用when替代了java中的switch,“:”符号改为了“->”。

3.指定onClick属性

    <Button
android:id="@+id/mButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="mButton3"
android:text="关闭"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@+id/mButton2" />
    fun mButton3(view: View) {
if (view.id == R.id.mButton3) {
finish()
}
}

代码中就实现了关闭当前Activity

以上

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,104
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,581
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,428
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,200
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,835
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,918