zoukankan      html  css  js  c++  java
  • 第一行Kotlin系列(一)kotlin按钮点击事件

    按钮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

    以上

  • 相关阅读:
    laravel 使用 php artisan make:model到指定目录(controller同理)
    Mysql常见的优化策略
    laravel路由别名
    laravel whereNotIn where子查詢
    phpstorm界面不停的indexing,不停的闪烁
    Linux下Redis开机自启(Centos6)
    数据结构常用算法
    困惑的前置操作与后置操作
    SSH框架整合中Hibernate实现Dao层常用结构
    过滤器与拦截器区别
  • 原文地址:https://www.cnblogs.com/MyXcc/p/12881053.html
Copyright © 2011-2022 走看看