[android] ConstraintLayout에서의 팝업창 구현

안드로이드 앱에서 팝업창을 구현하려면 일반적으로 다이얼로그를 사용하게 됩니다. 이번에는 ConstraintLayout을 이용하여 팝업창을 만드는 방법에 대해 알아보겠습니다.

1. 팝업창을 위한 Layout 생성

우선, 팝업창에 들어갈 디자인을 ConstraintLayout으로 만들어야 합니다. 예를 들어, popup_layout.xml이라는 이름의 파일을 만들어 다음과 같이 디자인할 수 있습니다.

<?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="wrap_content"
    android:background="@android:color/white">

    <TextView
        android:id="@+id/titleTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Welcome to the Popup"
        android:textSize="24sp"
        app:layout_constraintBottom_toTopOf="@+id/buttonClose"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/buttonClose"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Close"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

2. 팝업창을 띄우기 위한 코드 작성

그 다음으로는 팝업창을 띄우기 위한 코드를 작성해야 합니다. 아래 코드에서는 ConstraintLayout로 만든 popup_layout을 이용하여 팝업창을 띄우는 방법을 보여줍니다.

val inflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val view = inflater.inflate(R.layout.popup_layout, findViewById<ViewGroup>(R.id.popup))
val popupWindow = PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true)
popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0)

val buttonClose = view.findViewById<Button>(R.id.buttonClose)
buttonClose.setOnClickListener {
    popupWindow.dismiss()
}

위 코드에서는 LayoutInflater를 이용하여 popup_layout을 inflate하여 팝업창을 생성하고, PopupWindow를 통해 해당 팝업창을 띄우게 됩니다. 또한, Close 버튼을 클릭했을 때 팝업창을 닫도록 하는 동작도 구현되어 있습니다.

이렇게 ConstraintLayout을 이용하여 팝업창을 만드는 방법을 알아보았습니다.

더 자세한 내용은 아래 링크를 참고하세요.