build.gradle (Module: app)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' android { compileSdkVersion 26 defaultConfig { applicationId "com.phaisarn.ktapplication" minSdkVersion 21 targetSdkVersion 26 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" implementation 'com.android.support:appcompat-v7:26.1.0' implementation 'com.android.support.constraint:constraint-layout:1.1.3' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' implementation 'org.jetbrains.anko:anko-common:0.8.3' } |
บรรทัดที่ 34 : ใช้ไลบรารี่ anko เพื่อเรียกใช้ toast
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"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="Button1" /> </FrameLayout> |
บรรทัดที่ 9 : ปุ่มชื่อ button1
MainActivity.kt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package com.phaisarn.ktapplication import android.support.v7.app.AppCompatActivity import android.os.Bundle import kotlinx.android.synthetic.main.activity_main.* import org.jetbrains.anko.toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) button1.setOnClickListener { toast("Hello World!") } } } |
บรรทัดที่ 5 : import kotlinx.android.synthetic.main.activity_main.*
เพื่อให้อ้างถึงวิวในหน้า activity_main.xml ได้เลย โดยไม่ต้องสร้างตัวแปรแล้วใช้ findViewById()
บรรทัดที่ 14 : อ้างถึง button1
ที่อยู่ใน activity_main.xml ได้เลย โดยไม่ต้องใช้ findViewById()