【Kotlin/Android Studio】AlertDialogの使い方!DialogFragmentでカスタムダイアログ

この記事からわかること
- Android Studio/KotlinのAlertDialogの使い方
- アプリでダイアログ(ポップアップビュー)を実装する方法
- リストやチェックボックス、ラジオボタンなど
- DialogFragmentでカスタムダイアログを作成するには?
index
[open]
\ アプリをリリースしました /
環境
- Android Studio:Flamingo
- Kotlin:1.8.20
AlertDialogでダイアログを実装する方法
Androidでダイアログ(ポップアップビュー)を実装するにはAlertDialog
クラスを使用します。実装方法は簡単で「MainActivity.kt」にコードを書くだけで実装することが可能です。今回はボタンをタップされた時にダイアログが出る仕組みを実装していきます。まずはその前に「activity_main.xml」にボタンを設置しておきます。
<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/done_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Done"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
シンプルなダイアログ
まずはシンプルなダイアログを実装して使い方をみていきます。AlertDialog
クラスからBuilder
を呼び出し、引数にはContext
(ここではthis
)を渡します。そこからsetTitle
メソッドでタイトルをsetMessage
メソッドでメッセージをsetPositiveButton
メソッドでボタンを定義します。最後にshow
メソッドを実行することでダイアログが表示されます。
val button:Button = findViewById(R.id.done_button)
button.setOnClickListener {
AlertDialog.Builder(this)
.setTitle("ここにタイトル")
.setMessage("ダイアログのメッセージ")
.setPositiveButton("OK", { dialog, which ->
// ボタンクリック時の処理
})
.show()
}

アイコンをつける
setIcon
メソッドを使用することでダイアログに画像(アイコン)を設置することができます。
val button:Button = findViewById(R.id.done_button)
button.setOnClickListener {
AlertDialog.Builder(this)
.setTitle("ここにタイトル")
.setMessage("ダイアログのメッセージ")
.setPositiveButton("OK", { dialog, which ->
// ボタンクリック時の処理
})
.setIcon(R.mipmap.ic_launcher)
.show()
}

ボタンを2つ表示する
ボタンを2つ表示するにはsetPositiveButton
メソッドとsetNegativeButton
メソッドを使用します。setPositiveButton
メソッドで指定した方が右側にsetNegativeButton
メソッドが左側に来るように配置されます。
AlertDialog.Builder(this)
.setTitle("ここにタイトル")
.setMessage("ダイアログのメッセージ")
.setPositiveButton("OK", { dialog, which ->
// ボタンクリック時の処理
})
.setNegativeButton("キャンセル", { dialog, which ->
// ボタンクリック時の処理
})
.show()

3つ目のボタンを表示する
setNeutralButton
メソッドを使用することで3つ目のボタンを設置することができます。これはダイアログの左側に配置されます。3つ目と書きましたが、ボタンの定義が1つしかない状態でsetNeutralButton
メソッドを使用しても変わらずダイアログの左側に配置されます。
AlertDialog.Builder(this)
.setTitle("ここにタイトル")
.setMessage("ダイアログのメッセージ")
.setPositiveButton("OK", { dialog, which ->
// ボタンクリック時の処理
})
.setNegativeButton("キャンセル", { dialog, which ->
// ボタンクリック時の処理
})
.setNeutralButton("その他", { dialog, which ->
// ボタンクリック時の処理
})
.show()

ダイアログでリストを表示する
ダイアログ内でリストを表示するにはsetItems
メソッドを使用します。引数に表示させたいリストを渡します。
val list = arrayOf("kotlin","Swift","Dart")
AlertDialog.Builder(this)
.setTitle("アプリ開発言語")
.setItems(list, { dialog, which ->
// ボタンクリック時の処理
})
.setPositiveButton("OK", { dialog, which ->
// ボタンクリック時の処理
})
.show()

ダイアログでチェックボックスを表示する
ダイアログ内でチェックボックスを表示するにはsetMultiChoiceItems
メソッドを使用します。引数に表示させたいリストとチェックフラグを渡します。
val list = arrayOf("kotlin","Swift","Dart")
val checkedFlags = booleanArrayOf(true, false, false)
AlertDialog.Builder(this)
.setTitle("アプリ開発言語")
.setMultiChoiceItems(list, checkedFlags, { dialog, which, isChecked ->
// ボタンクリック時の処理
})
.setPositiveButton("OK", { dialog, which ->
// ボタンクリック時の処理
})
.show()

ダイアログでラジオボタンを表示する
ダイアログ内でラジオボタンを表示するにはsetMultiChoiceItems
メソッドを使用します。引数に表示させたいリストとデフォルトでチェック状態にするインデックス番号を渡します。
val list = arrayOf("kotlin","Swift","Dart")
AlertDialog.Builder(this)
.setTitle("アプリ開発言語")
.setSingleChoiceItems(list, 0, { dialog, which ->
// ボタンクリック時の処理
})
.setPositiveButton("OK", { dialog, which ->
// ボタンクリック時の処理
})
.show()

カスタムダイアログ:DialogFragment
まずはDialogFragment
を使用してFragment側にダイアログの処理を移してみます。まずは適当にCustomDialogFragment
を作成します。DialogFragment
を継承させ、onCreateDialog
メソッド内でダイアログ構築処理を実装し、最後にbuilder.create()
を実行し返します。
import android.app.Dialog
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
class CustomDialogFragment: DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val builder = AlertDialog.Builder(this.requireContext())
builder.setTitle("ここにタイトル")
.setMessage("ダイアログのメッセージ")
.setPositiveButton("OK", { dialog, which ->
// ボタンクリック時の処理
})
.show()
return builder.create()
}
}
あとは「MainActivity.kt」側から以下のようにすっきりと呼び出すことができるようになります。
val button:Button = findViewById(R.id.done_button)
button.setOnClickListener{
val dialog = CustomDialogFragment()
dialog.show(supportFragmentManager, "custom")
}

独自のレイアウトダイアログを作成する
ダイアログの中身を独自にカスタマイズしたものを実装するにはレイアウトファイルを用意し、それをダイアログとして表示させる方法で実現できます。まずは以下のように適当なレイアウトファイルを用意します。
<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">
<EditText
android:id="@+id/editTextText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="text"
android:text="Name"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<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_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editTextText" />
</androidx.constraintlayout.widget.ConstraintLayout>
続いてCustomDialogFragmentクラスのonCreateDialog
メソッド内で以下のようにdialog_fragment
レイアウトをインフレートしsetView
メソッドでAlertDialog.Builder
インスタンスに渡します。
class CustomDialogFragment: DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val builder = AlertDialog.Builder(this.requireContext())
val inflater = this.requireActivity().layoutInflater
val dialog = inflater.inflate(R.layout.dialog_fragment,null)
builder.setView(dialog)
return builder.create()
}
}
最後にMainActivityクラスでCustomDialogFragmentクラスをインスタンス化しshow
メソッドを呼び出すことで実装できます。
val button:Button = findViewById(R.id.done_button)
button.setOnClickListener{
val dialog = CustomDialogFragment()
dialog.show(supportFragmentManager, "custom")
}

まだまだ勉強中ですので間違っている点や至らぬ点がありましたら教えていただけると助かります。
ご覧いただきありがとうございました。
個人開発に限界を感じたらiOSに特化したプログラミングスクール「iOSアカデミア」も検討してみてください!無料相談可能で「最短・最速」でiOSエンジニアになれるように手助けしてくれます。