시배's Android
Compose | Hilt를 사용하고 있을 경우 activity 가져오기 본문
val context = LocalContext.current
val activity = context as AppCompatActivity
일반적으로 compose에서 activity가 필요로 할 경우 위와 같은 코드를 통해 가져올 수 있습니다.

하지만 Hilt가 적용되어 있을 경우 이 부분에서는 크래시가 발생하였고 FragmentContextWrapper를 Activity로 변환할 수 없다는 내용이었습니다. FragmentContextWrapper 클래스는 ContextWrapper를 상속받고 있었고, HIlt 내부에서 사용하는 ViewComponentManager에서 관리되고 있었습니다.
해결 방법은 FragmentComponentManager 클래스의 findActivity 메서드를 이용하는 것입니다.
val context = LocalContext.current
val activity = FragmentComponentManager.findActivity(context)
public static final Context findActivity(Context context) {
while (context instanceof ContextWrapper
&& !(context instanceof Activity)) {
context = ((ContextWrapper) context).getBaseContext();
}
return context;
}
findActivity의 구현을 살펴 보면, 위와 같습니다.
Activity 객체에 도달할 때 까지 반복문을 수행하여 찾은 context를 return 해주고 있습니다.
'Android > Compose' 카테고리의 다른 글
Compose | 이미지 컬러 추출하기 (Palette, Coil) (0) | 2023.08.06 |
---|---|
Compose | Compose LazyColumn에서 FadingEdge 구현하기 (0) | 2023.07.26 |
Compose | 컴포즈 커스텀 레이아웃 구현하기 (1) | 2023.07.16 |
Compose | Compose로 CollapsingToolbarLayout 구현하기 (0) | 2023.07.12 |
Compose | Recomposition Optimistic (0) | 2023.07.10 |