본문 바로가기

안드로이드

[Android] 프래그먼트에서 gif 로딩 다이얼로그(Dialog Fragment) 띄우기

개요

안드로이드에서는 다이얼로그를 액티비티에서 띄우는 것과 프래그먼트에서 띄우는 것에 대해 차이가 난다. Dialog Fragment를 활용하면 어느 프래그먼트에서는 Fragment Manger를 통해 다이얼로그를 띄울 수 있다. Dialog Fragment도 결국 Fragment이기 때문이다. 

 

이번 포스팅은 직전의 포스팅([Android] 액티비티에서 gif를 이용한 로딩 다이얼로그 띄우기 (tistory.com))과 연관이 있다. 종속성 추가, Base Application 생성 등의 과정은 생략한다.

 

1. 커스텀 다이얼로그 프래그먼트 구현

class ProgressDialogFragment :DialogFragment(){
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = AppCompatDialog(activity)
        dialog.apply {
            setCancelable(false)
            window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            setContentView(R.layout.loading_dialog)
        }
        Glide.with(activity!!).load(R.raw.rolling_loader)
                .apply(RequestOptions().override(50,50))
                .into(dialog.findViewById<ImageView>(R.id.load_image_view) as ImageView)
        return dialog
    }
}

단순히 onCreateDialog에서 다이얼로그를 생성하로 반환하면 된다.

 

2. BaseApplication에 Dialog On, Off 메서드 구현

class BaseApplication : Application(){

    override fun onCreate() {
        super.onCreate()
        instance=this
    }


    fun progressOnInFragment(fragment: Fragment?){
        if(fragment==null || fragment.isDetached)
            return

        if(fragmentDialog==null || (fragmentDialog!=null && !fragmentDialog!!.isVisible)) {
            fragmentDialog = ProgressDialogFragment()
            fragmentDialog!!.show(fragment.childFragmentManager,"PROGRESS")
        }
    }


    fun progressOffInFragment(){
        if(fragmentDialog!=null && fragmentDialog!!.isResumed) {
            fragmentDialog!!.dismiss()
        }
    }

    companion object {
        lateinit var instance : BaseApplication
            private set //Only BaseApplication set the instance value
        var fragmentDialog: ProgressDialogFragment? = null
    }

}

progressOnInFragment에서 DialogFragment 객체를 생성하고 show() 메서드를 통해 다이얼로그를 띄운다. 그리고, 작업이 종료될 경우 progressOffInFragment에서 dismiss() 메서드를 호출한다.

 

이후 저번 포스팅 처럼 Util에서 메서드를 구현한 뒤, 프래그먼트 내의 적절한 위치에서 해당 메서드를 호출하면 된다.