최데브는 오늘도 프로그래밍을 한다.

안드로이드 Dialog 만들기 (kotiln) 본문

Android

안드로이드 Dialog 만들기 (kotiln)

최데브 2021. 7. 30. 10:34
반응형

앱을 만들다보면 DIalog를 만들때다 종종 있다. 그럴때 어떻게 해야하는지 

코드로 알아보자.

 

아래는 실제 Dialog 코드다.

 

class MyDialog(context: Context, layoutId: Int) : Dialog(context) {
    var detector: GestureDetector? = null // 다이얼로그가 나와있을때 손가락 제스쳐에 따른 행동을 구현하기 위함
    protected var mContext: Context
    private val iv: ImageView
    private val text: String

    companion object {
        private const val SWIPE_MIN_DISTANCE = 120 // 제스쳐에 사용될 상수
        private const val SWIPE_THRESHOLD_VELOCITY = 200// 제스쳐에 사용될 상수
    }

    init { // kotlin 에서 사용되는 초기화 구간
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        setContentView(layoutId)
        mContext = context
        iv = findViewById<View>(R.id.iv) as ImageView // dialog 에서 사용할 이미지뷰 초기화

        setCancelable(true) //dialog가 취소가 되는지
        setCanceledOnTouchOutside(true) // 바깥화면을 눌렀을때 닫기는지 설정
        
        //손가락 제스쳐에 따른 행동들 구현
        detector = GestureDetector(context, object : GestureDetector.OnGestureListener {
            override fun onDown(e: MotionEvent): Boolean { 
                return false
            }

            override fun onShowPress(e: MotionEvent) {}
            override fun onSingleTapUp(e: MotionEvent): Boolean {
                return false
            }

            override fun onScroll(e1: MotionEvent, e2: MotionEvent, distanceX: Float, distanceY: Float
            ): Boolean {
                return false
            }

            override fun onLongPress(e: MotionEvent) {}
            override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
                if (e2.y - e1.y > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {
                    dismiss()
                }
                return true
            }
        })
        
        // 다이얼로그의 크기를 조정 할 수 있음.
        val window = window // dialog 의 window 를 알아옴.
        if (window != null) {
            val params = window.attributes
            // 화면에 띄울 크기
            params.width = WindowManager.LayoutParams.MATCH_PARENT // 크기를 이렇게 조정가능
            params.height = WindowManager.LayoutParams.WRAP_CONTENT

            // 다이얼로그 뒤 배경 Capacity
            params.dimAmount = 0.4f // 다이얼로그가 나왔을때 뒷배경의 투명도를 조정

            // 열기&닫기 시 애니메이션 설정
            params.windowAnimations = R.style.AnimationBottomPopupStyle // 본인이 애니메이션을 만들었다면 이렇게
            window.attributes = params

            // 다이얼로그 뒷 배경 투명
            window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))

            // UI 하단 정렬
            window.setGravity(Gravity.BOTTOM)
        }
    }
}

 

 

 

그럼 액티비티에서 사용은 어떻게 할까?

 

이렇게 선언을 하고 

var myDialog = MyDialog(this, layout.my_qr_layout

onCreate() 안에서

 

myDialog .show() 로 실행하면 다이얼로그가 나온다.

 

 

애니메이션의 경우는 나는

 

themes.xml 에서 

 

<style name="AnimationBottomPopupStyle">
<item name="android:windowEnterAnimation">@anim/open_bottom</item>
<item name="android:windowExitAnimation">@anim/close_bottom</item>
</style>

 

이렇게 만들어주고 res 폴더아래 anim 폴더를 만들고 그 아래에 

밑의 두 파일을 생성해줬다.

 

 

open_bottom.xml

 

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_interpolator">
<translate
android:fromYDelta="100%"
android:toYDelta="0%"
android:duration="200"/>
</set>

 

close_bottom.xml

 

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_interpolator">
<translate
android:fromYDelta="0%"
android:toYDelta= "100%"
android:duration="200"/>
</set>

 

 

이 코드만 있어도 간단한 DIalog 를 사용할 수 있다~

반응형
Comments