안드로이드/개발관련(Kotlin)

안드로이드 커스텀 다이얼로그(CustomDialog, Kotlin)

닉네임못짓는사람 2021. 12. 24. 04:56
반응형

다이얼로그는 사용자에게 결정을 내리거나 추가 정보를 입력하라는 메시지를 표시하는 창이다.

다이얼로그는 보통 화면을 가득 채우지 않고, 사용자가 다음으로 진행하기 전에 조치를 취해야 하는 이벤트에 사용된다.

 

이런 다이얼로그를 생성하기 위한 일반적인 방법으로 AlertDialog를 사용하는 방법이 있는데,

이 글에선 AlertDialog가 아니라 사용자가 직접 정의하는 CustomDialog를 만드는 법에 대해서 알아보자.

CustomDialog


기본적으로 다이얼로그라는 창을 사용자에게 보여주기 위해선 해당 창을 디자인해야 할 것이다.

그러니 가장 처음으로 우리가 만들 CustomDialog의 레이아웃을 만들어보도록 하자.

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


    <EditText
        android:id="@+id/editTextTextPersonName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="EditText" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal">

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize = "15sp"
            android:layout_marginRight="20dp"
            android:text="확인" />

        <Button
            android:id="@+id/button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize = "15sp"
            android:layout_marginLeft="20dp"
            android:text="취소" />
    </LinearLayout>

</LinearLayout>

여기서 사용할 레이아웃은 위와 같이 아주 간단하게 만들어봤다.

 

다음으로 CustomDialog클래스를 만들어주는데, 이 글에선 DialogFragment를 상속받는 클래스를 하나 만들어주도록 하자.

class CustomDialog: DialogFragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val binding = DialogCustomBinding.inflate(inflater, container, false)

        return binding.root
    }
}

 

그럼 이제 메인 액티비티로 넘어가서 위와 같이 코드를 작성하여,

화면에 배치된 버튼을 클릭하면 dialog가 나오도록 해보자.

binding.showDialogButton.setOnClickListener {
      CustomDialog().show(supportFragmentManager, "")
}

실행을 하면 위와 같이 우리가 만든 CustomDialog가 화면에 나오는것을 볼 수 있다.

그런데, AlertDialog와는 달리 모양이 조금 보기안좋은데, 다시 CustomDialog클래스로 돌아가서 코드를 좀 수정해보자.

class CustomDialog: DialogFragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val binding = DialogCustomBinding.inflate(inflater, container, false)

        dialog?.window?.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.WRAP_CONTENT)
        dialog?.setCancelable(true)

        return binding.root
    }
}

코드를 위와 같이 수정했는데, window.setLayout을 통해서 우리가 만든 Dialog의 크기를 조절할 수 있다.

또한 setCancel~ 코드를 통해 Dialog의 바깥쪽을 터치하면 Dialog가 꺼지도록 만들 수 있다.

그럼 이제 수정한 코드를 적용하여 다시 실행해보자.

방금 전 보다는 확실히 더 보기 좋은 모양으로 바뀐 것 같다.

이러한 부분들을 활용하여 자신이 원하는 Dialog를 만들어 사용할 수 있다.

CustomDialog에서 값 전달


아무런 작업도 하지 않은 경우 위의 코드까지만 작성한다면, 확인이나 취소 버튼을 눌러도 아무 일도 일어나지 않는다.

이렇게 CustomDialog를 만든것은 좋지만, 우리는 이를 통해서 무언가 작업을 수행해야 한다.

이를 위해선 당연히 값(데이터)가 오고 가고, 이벤트들이 적용돼야 할 텐데 이 방법에 대해서 알아보도록 하자.

 

Kotlin에선 고차함수를 지원하기 때문에 dialog를 호출하는 화면에서 원하는 함수를 파라미터로 전달하여 동작을 수행하도록 할 수 있다.

class CustomDialog(
    private val button2Event: () -> Unit,
    private val button3Event: () -> Unit
): DialogFragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val binding = DialogCustomBinding.inflate(inflater, container, false)

        dialog?.window?.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.WRAP_CONTENT)
        dialog?.setCancelable(true)

        binding.button2.setOnClickListener {
            button2Event()
        }

        binding.button3.setOnClickListener {
            button3Event()
        }

        return binding.root
    }
}

 

이제 바꾼 코드를 실행하여 확인해보도록 하자.

이렇게 CustomDialog를 만들어 값을 전달하는 방법까지 알아보았다.

반응형