0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

AlertDialogをカスタムする

0
Posted at

Androidで確認ダイアログを表示するなどで手軽に使用する方法でAlertDialogがあります。このレイアウトをカスタムする方法をメモします。

通常は次のように使用します。

AlertDialog.Builder(this)
    .setTitle("確認")
    .setMessage("削除しますか?")
    .setPositiveButton("OK", null)
    .show()

ここからsetView()を使用することでカスタマイズの幅が広がります。

名前を入力するダイアログを作成します。

dialog_input.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="20dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="名前を入力してください" />

    <EditText
        android:id="@+id/editName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

レイアウトを読み込み、AlertDialogへセットする

val view = layoutInflater.inflate(R.layout.dialog_input,null)
val dialog = AlertDialog.Builder(this)
    .setTitle("入力")
    .setView(view)
    .setPositiveButton("OK", null)
    .setNegativeButton("キャンセル", null)
    .create()

dialog.show()

これでオリジナルレイアウトを表示できます。

ボタン押下時に処理を追加する

setPositiveButton()は押下すると自動的にダイアログが閉じます。追加の処理を行いたい場合は、一度create()してからボタンへリスナーを設定します。

val dialog = AlertDialog.Builder(this)
    .setTitle("入力")
    .setView(binding.root)
    .setPositiveButton("OK", null)
    .setNegativeButton("キャンセル", null)
    .create()

dialog.setOnShowListener {
    dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
        val name = binding.editName.text.toString()
        if (name.isBlank()) {
            Toast.makeText(context, "入力してください", Toast.LENGTH_SHORT).show()
            return@setOnClickListener
        }
        dialog.dismiss()
    }
}

dialog.show()

角丸デザインを採用している場合は、ダイアログの背景を透明にします。これによりレイアウト側で設定した角丸デザインがそのまま表示されます。

dialog.window?.setBackgroundDrawable((Color.TRANSPARENT.toDrawable())
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?