본문 바로가기

android/Issue

Fragment 내에 ViewPager 를 사용한 Fragment 호스팅 시 Navigation 문제

상황
AFragment 내에 ViewPager2 를 사용하여 BFragment 를 호스팅하고 있음
BFragment 의 특정 UI 요소를 클릭하면 CFragment 로 navigate 되어야 하는 상황

 

문제 발생

BFragment 의 UI 요소를 클릭하여 CFragment 로 navigate 하는 순간

java.lang.IllegalArgumentException: Navigation action/destination com.xxx.xxx:id/action_BFragment_to_CFragment cannot be found from the current destination Destination(com.xxx.xxx:id/aFragment) label=AFragment class=com.xxx.xxx.AFragment  예외가 발생함

 

원인
현재 BackStack 최상단(Current Destination)은 AFragment 인데 BFragment 에 추가된 action 을 호출하려고 하여 예외가 발생, AFragment 에서 ViewPager 를 통해 BFragment 를 호스팅하여 BFragment 가 화면에 보이는 상황이더라도 BFragment 가 BackStack 최상단에 노출되는 것이 아니라 AFragment 가 여전히 BackStack 최상단에 존재하는 상태

 

해결 방법(미해결)

기존의 Navigation Graph 에서 BFragment 에서 CFragment 로 이동하도록 설정된 action 을 AFragment 에서 CFragment 로 이동하도록 action 을 변경하고,  BFragment 의 특정 UI 요소가 클릭되었을 때 CFragment 에 전달해야 하는 값을 NavGraph Scope 의 ViewModel 에 저장하고 AFragment 에서 해당 ViewModel 요소를 관찰하는 방식으로 우회적으로 해결할 수 있을 것 같으나 깔끔한 해결책은 아닌 것 같음