activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Click Me!" /> </android.support.constraint.ConstraintLayout> |
MainActivity.kt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.phaisarn.ktapplication import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.View import kotlinx.android.synthetic.main.activity_main.* import android.widget.Toast class MainActivity : AppCompatActivity(), View.OnClickListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) button.setOnClickListener(this) } override fun onClick(view: View) { Toast.makeText(this, "Hello World!", Toast.LENGTH_SHORT).show() } } |
บรรทัดที่ 9 : ทำการ implements View.OnClickListener
แต่ไม่ต้องพิมพ์คำว่า implements
บรรทัดที่ 15 : setOnClickListener(this)
ไปที่ this
บรรทัดที่ 18 : override ฟังก์ชัน onClick()