トーストとアラート
ユーザーにメッセージを表示する場合、主な手段として「トースト」と「アラートダイアログ」の二種類があります。
レイアウト
とりあえずレイアウトファイルに次のようにボタンを二つ作成します。
トーストを表示するボタンとアラートダイアログを表示するボタンです。

今回は適当に、IDとTEXTだけに注目してもらえればOKです。
<Button
android:id="@+id/buttonToast"
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_toTopOf="parent" />
<Button
android:id="@+id/buttonAlert"
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/buttonToast" />
アクティビティ
上で配置したボタンそれぞれを押したときのアクションを記述します。
「トースト」ボタンを押すとトーストが表示され、「アラート」ボタンを押すとアラートダイアログが表示されるだけの単純なものです。
以下をメインアクティビティに追記します
var buttonToast:Button = findViewById(R.id.buttonToast)
var buttonAlert:Button=findViewById(R.id.buttonAlert)
//トースト処理
buttonToast.setOnClickListener {
Toast.makeText(this,"トースト表示", Toast.LENGTH_LONG).show()
}
//アラートダイアログ処理
buttonAlert.setOnClickListener {
AlertDialog.Builder(this)
.setTitle("エラー")
.setMessage("メッセージ")
.setPositiveButton("OK",null)
.show()
}
| 「トースト」ボタンを押したとき | 「アラート」ボタンを押したとき |
 |
 |