kotlin click event

Layout file

    <TextView
        android:id="@+id/test"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:gravity="center"
        android:text="测试点击事件"
        android:textSize="18sp" />

Method 1: Anonymous inner class

tv_test.setOnClickListener {
    
    
    Toast.makeText(this, "点击了",Toast.LENGTH_SHORT).show()
}

Method 2: Implement the onClick method of the View.OnClickListener interface

class MainActivity : AppCompatActivity(), View.OnClickListener {
    
    

    override fun onCreate(savedInstanceState: Bundle?) {
    
    
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        tv_test.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
    
    
        when (v?.id) {
    
    
            R.id.tv_test	->
                Toast.makeText(this, "点击了", Toast.LENGTH_SHORT).show()
        }
    }

}

Method 3: Add the onClick attribute to the control, and add the corresponding method to the corresponding activity or fragment

Layout file after adding onClick attribute

    <TextView
        android:id="@+id/test"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:gravity="center"
        android:onClick="testClick"
        android:text="测试点击事件"
        android:textSize="18sp" />

After adding, there will be a red underline in "testClick", because there is no corresponding method in the corresponding activity or fragment, you can alter+enter to prompt, select the red box to automatically generate, or you can manually add
Insert picture description here
the activity after adding the corresponding method

class MainActivity : AppCompatActivity() {
    
    

    override fun onCreate(savedInstanceState: Bundle?) {
    
    
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    fun testClick(view: View) {
    
    
        Toast.makeText(this, "点击了", Toast.LENGTH_SHORT).show()
    }

}

Only this record, if you have any questions, please ask, thank you

Guess you like

Origin blog.csdn.net/nongminkouhao/article/details/108233486