[Android開発]Buttonのクリックイベントを設定する方法
最近、KotolinでAndroidアプリの開発に挑戦しています。そこで、初歩的なところからボタンをタップしたときにログに文字を出力する仕組みをハンズオンします。
Coding
package com.example.myapplication
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<Button>(R.id.button)
.setOnClickListener {
exportDebugLog("ButtonClicked!!!")
}
exportDebugLog("OnCreate")
}
private fun exportDebugLog(message :String){
Log.d("TestApp", message)
}
}
MainActivity.kt
<?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">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
activity_main.xml
findViewByIdでButtonのidを指定します。Buttonのidはxmlに記載のある通りbuttonとしています。
その要素に対してsetOnClickListenerによって、クリックされた時のイベントを設定します。
Result


Acknowledgements
Add buttons to your app | Android Developers

【AndroidStudio】ボタンのイベントハンドラ設定方法 - Qiita
【参考】Log Log Logger:レイアウトエディターからのボタンonClickイベントハンドラの生成方法ボタンのクリックイベントをどう実装すればいいのか分からない…VB系言語では、イベント…
