Kotlinは、Javaの統合開発環境であるIntelliJ IDEAで有名なJetBrainsが開発したオブジェクト指向プログラミング言語です。言語構文自体はJavaとは互換性がない独自方式ですが、コンパイルされたコードはJava VM(仮想マシン)上で動作するため、これまでのJava資産の多くを流用できるという特徴を持っています。
Google I/O 2017のキーノートでは、AndroidチームがKotlinを公式にサポートするという発表がありました。また、最近リリースされたAndroid Studio 3.0では、Kotlin開発用のプラグインが最初から組み込まれているなど、注目を集めています。
本記事ではkotlinの入門編として簡単なAndroidアプリの作成について紹介していきます。
上記画像のように画面が表示されボタンを押下すると今日の運勢的なものが表示されるという簡単なアプリです。
kotlinではjavaと同じようにレイアウトファイルと動作用kotlinファイルの二つをによってアプリを定義しています。
以下が動的kotlinファイルになります。
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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">
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="todays"
android:textSize="50sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onButton"
android:text="check today"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.821" />
</androidx.constraintlayout.widget.ConstraintLayout>
運勢が出力される部分が画面の中心に来るように設定しています。
中心に来るように指定している箇所は以下です。
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
また以下の枠組みに区別することでボタン機能を付与しています
<Button>
</Button>
以上ざっくり解説です
またkotlinファイルについては以下のものになります
package com.example.check_today
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
val s = arrayOf("大凶", "凶", "吉", "大吉")
fun onButton(v: View) {
val r = Random().nextInt(4)
tv.text = s[r]
}
}
動きの解説については省きますが、以下の部分でレイアウトファイルとkotlinファイルの結びつけを行っています。
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
以下ではボタン動作を指定している
fun onButton(v: View) {
val r = Random().nextInt(4)
tv.text = s[r]
}
またレイアウトファイルのid(今回でいう占い結果の可変部分)を以下のように指定することによって、レイアウトファイルのテキストを動的にすることができる。
tv.text = s[r]
いかがだったでしょうか。
次回も自分が勉強中に作成したkotlinの簡単なアプリを紹介していきます。