오늘도 삽질중

Android View 의 절대좌표가 맞지 않을경우 본문

안드로이드

Android View 의 절대좌표가 맞지 않을경우

Choi3950 2021. 12. 21. 01:44
반응형

뷰의 절대좌표 값을 가져와서 마스킹을 하든 별도의 작업을 해야되는 경우가 있다.

여러 블로그에 절대좌표값을 가져오는 내용이 많으므로 그 내용은 생략하고

구현중에 절대좌표 값이 맞지 않는 상황이 있었다.

왜 맞지 않을까 생각을 해봤는데....

자식뷰를 바로 가져오는게 아니라 자식뷰가 부모가 되는 다른 자식뷰를 가져오기 때문이라고 생각하고 있다.

왜냐면 바로 자식뷰의 좌표값을 가져올땐 이러한 문제가 발생하지 않았기 때문이다.

 

 

암튼 문제가 된 상황을 좀 더 쉽게 설명하면

나의 경우에는 inclue 한 레이아웃에서 특정 뷰의 좌표를 가져와야 하는데 좌표값이 어긋나는 상황이 있었다.

코드로 보면 아래와 같은 상황이다.

....
....

 <com.facebook.shimmer.ShimmerFrameLayout
        android:id="@+id/shimmer_layout"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="18dp"
        android:paddingStart="16dp"
        android:paddingEnd="16dp"
        app:shimmer_auto_start="false"
        app:layout_constraintTop_toBottomOf="@id/group_tabBar"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
            <include
                android:id="@+id/masking_include_shimmer"
                layout="@layout/row_explore_shimmer"
                />
            <include layout="@layout/row_explore_shimmer"/>
            <include layout="@layout/row_explore_shimmer"/>
        </LinearLayout>

    </com.facebook.shimmer.ShimmerFrameLayout>
    
    ....
    ....

스켈레톤 Ui를 구현하기 위해 inclue로 뷰를 세팅하고 masking_include_shimmer 에 있는 특정 뷰의 좌표 값을 가져와야 했다.

 

 

 

열심히 구글링을 해보고 아래와 같은 소스로 정확한 좌표값을 가져올수 있었다.

            val targetViewCoordinateArray = IntArray(2)
            val rootViewCoordinateArray = IntArray(2)
            binding.maskingIncludeShimmer.maskingTargetView.getLocationInWindow(targetViewCoordinateArray)

            val rootView = view?.rootView?.findViewById<ViewGroup>(android.R.id.content)
            rootView?.getLocationInWindow(rootViewCoordinateArray)

            val targetViewX = targetViewCoordinateArray[0]
            val targetViewY = targetViewCoordinateArray[1]

            val realTargetViewX = targetViewCoordinateArray[0] - rootViewCoordinateArray[0]
            val realTargetViewY = targetViewCoordinateArray[1] - rootViewCoordinateArray[1]

핵심은 rootView의 좌표값을 가져와서

내가 알아야할 타겟뷰의 좌표값과 계산을 해서 올바른 값을 구하였다.

(view?.rootView? 소스에 ? 가 붙은건 해당 소스는 프래그먼트에서 작성됬기 때문입니다.)

 

 

해당 내용외에 좌표를 구하는 여러 방법이 아래 스택오버플로우에 많이 기재되있으니 참고하는게 좋을꺼 같다.

https://stackoverflow.com/questions/3619693/getting-views-coordinates-relative-to-the-root-layout

반응형
Comments