LoginSignup
1
0

More than 1 year has passed since last update.

【Android】ダイアログのmatch_parentについて

Last updated at Posted at 2021-06-10

ダイアログの幅・高さいっぱいに広げるのに手間取ったのでメモ。
あまり使う場面はないと思うが。

AlertDialog

AlertDialogは比較的簡単に実装可能なため、これを使用していた。
ただ、これだと幅・高さいっぱいに広げられない。

MainActivity.kt
val dialog = AlertDialog.Builder(this).apply {
    setTitle("タイトル")
    setMessage("メッセージ")
    setNegativeButton("閉じる") { dialog, _ -> dialog.cancel() }
}.create()

//このようにmatch_parentを使おうとしても意味がない
dialog.window?.setLayout(
    ViewGroup.LayoutParams.MATCH_PARENT,
    ViewGroup.LayoutParams.MATCH_PARENT
)

dialog.show()

Dialog

通常のダイアログを使用すると、幅・高さいっぱいに広げることができる。

まずダイアログのレイアウト作成。

test_dialog.xml
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:gravity="center"
    android:orientation="vertical"
    android:paddingHorizontal="60dp"
    android:paddingVertical="20dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="start"
        android:text="タイトル"
        android:textSize="20sp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="start"
        android:text="メッセージ"
        android:textSize="18sp" />

    <Button
        android:id="@+id/button"
        style="?android:attr/borderlessButtonStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end"
        android:text="閉じる"
        android:textColor="@color/black" />
</LinearLayout>

次に処理部分の作成。ここでmatch_parent指定。

TestDialogFragment.kt
class TestDialogFragment : DialogFragment() {

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return Dialog(requireContext()).apply {
            val binding = TestDialogBinding.inflate(LayoutInflater.from(context))

            binding.button.setOnClickListener {
                dismiss()
            }
            setContentView(binding.root)

            //ここで幅・高さをmatch_parentにする
            window?.setLayout(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
        }
    }
}

最後にMainActivityでダイアログ表示

MainActivity.kt
TestDialogFragment().show(supportFragmentManager, TestDialogFragment::class.java.simpleName)
1
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
1
0