

↑↑改訂版はこちら↑↑
以下は旧版の情報になります
↓↓↓
AndroidStudioで、簡単なタッチボタンアプリのプログラミング実況します。
今回はkotlinです。
kotlinはざっくり言うと「javaの後継的な言語」です。
javaをもっとシンプルにしよう、的な感じでAndroid開発を中心に、急速に普及している言語です。
環境:AndroidStudio4.1.3
▼動画解説
▼テキスト
注意:わりに最近、下記↓インポート文の利用が廃止(syntheticsがKotlin 1.4.20よりdeprecated)になったようです。import kotlinx.android.synthetic.main.activity_main.*
少し前までの書籍等は、上記インポート文を使っていると思われますので注意が必要です。
▼XML
<?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:layout_marginTop="24dp"
android:text="TextView"
android:textSize="30sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btnDog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="いぬ"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tv" />
<Button
android:id="@+id/btnCat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ねこ"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btnDog" />
<Button
android:id="@+id/btnClear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="クリア"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btnCat" />
</androidx.constraintlayout.widget.ConstraintLayout>
▼Kotlin
package com.example.touchapp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//1)idを取得
var tx:TextView =findViewById(R.id.tv)
var btn1:Button = findViewById(R.id.btnDog)
var btn2:Button = findViewById(R.id.btnCat)
var btn3:Button = findViewById(R.id.btnClear)
//2)クリック処理
btn1.setOnClickListener {
tx.text = "いぬ"
}
btn2.setOnClickListener {
tx.text = "ねこ"
}
btn3.setOnClickListener {
tx.text = "..."
}
}
}


