본문 바로가기

android

DialogFragment width 조정

앱을 개발하던 중 Dialog 가 필요해서 적용을 하기위해, DialogFragment 의 레이아웃의 width 를 match_parent 로 주고 margin 값을 이용해서 양쪽 여백을 만들려고 했으나 예상했던것과 다르게 동작하는 문제가 발생했습니다.

검색을 해보니 나와 비슷한 문제를 겪으신 분들이 많은 것 같습니다.  그 중 하나의 솔루션을 발견했고 적용한 결과 처음 원했던 대로 스크린 width 의 90%만 차지하는 Dialog 를 만들 수 있었습니다.

 

<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"
    tools:context=".presentation.view.main.daily_record.WriteDailyRecordFragment">
	
	...
	
</androidx.constraintlayout.widget.ConstraintLayout>

 

 

override fun onResume() {
	super.onResume()
	resizeDialog()
}

private fun resizeDialog() {
	val windowManager = requireActivity().getSystemService(Context.WINDOW_SERVICE) as WindowManager
        
	//getDefaultDisplay 는 API Level 30에서 deprecate 되었기 때문에 분기처리를 해줍니다.
	val width: Int = if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
		val windowMatrix = windowManager.currentWindowMetrics
		val insets = windowMatrix.windowInsets.getInsetsIgnoringVisibility(WindowInsets.Type.systemBars())
            
		//System Bar 크기를 포함하는 영역의 width 에서 인셋 크기를 빼서 가로 사이즈를 구합니다.
		windowMatrix.bounds.width() - insets.left - insets.right

	} else {
		//API Level 30 미만의 기기에서는 getSize 를 이용하여 가로 사이즈를 구합니다.
		val display = windowManager.defaultDisplay
		val size = Point()
		display.getSize(size)
		size.x
	}

	//현재 Window 의 속성을 가져옵니다.
	val layoutParams = dialog?.window?.attributes
		
	//LayoutParam 을 이용하여 현재 Dialog Fragment 가 부모 뷰에 90% 크기로 배치되야 한다고 설정합니다.
	layoutParams?.width = (width * 0.9).toInt()
	dialog?.window?.attributes = layoutParams as WindowManager.LayoutParams
}

'android' 카테고리의 다른 글

Android 권한  (0) 2022.10.27
Firebase Ream-Time Database Paging 처리  (1) 2022.10.25
Frgament 통신  (0) 2022.10.12
Fragment Transaction 동작 분석  (0) 2022.10.10
registerForActivityResult 메서드의 동작과정  (0) 2022.02.03