8

I have this code where I show Dialog Fragment when clicking a viewHolder item in Adapter

 SpecialRequestNotFoundBottomSheetDialog {
            requestItem?.specialRequestEntity?.id?.let { id -> onCancelReasonsSelected(id, it) }
        }.show(itemView.context as AppCompatActivity).supportFragmentManager)

recently I'm migrating to Hilt and I got class cast exception, looks like Hilt wrapping the context and I can't get the parent Activity to get the required FragmentManager to show the Dialog

Mohamed Ibrahim
  • 3,714
  • 2
  • 22
  • 44

3 Answers3

26

I read source code find this solution FragmentComponentManager.findActivity(view.context) as Activity

stronglee1346
  • 276
  • 3
  • 3
16

I may found a workaround to this crash by checking the Context type and getting the BaseContext. Here's what I'm using now. I don't know if there's a better way to do it with Hilt.

private fun activityContext(): Context? {
    val context = itemView.context
    return if (context is ViewComponentManager.FragmentContextWrapper) {
        context.baseContext
    } else context
}
Mohamed Ibrahim
  • 3,714
  • 2
  • 22
  • 44
0

In my case, my custom view is in the library module i.e: ("com.android.library"), and I am using hilt in my App module i.e: ("com.android.application") due to this my application is crashing. because I am using the Hilt library in my App Module, and context instances are created by the Hilt library. and I am unable to find fragmentManger.

so as a workaround I have to add Hilt in my library module and then I used the below code to find the FragmentManger

private FragmentManager getFragmentManager(@NonNull Context mContext) {
        if (mContext instanceof AppCompatActivity) {
            return ((AppCompatActivity) mContext).getSupportFragmentManager();
        } else if (mContext instanceof ContextThemeWrapper) {
            return getFragmentManager(((ContextThemeWrapper) mContext).getBaseContext());
        }
// below if clause is for hilt library
 else if (mContext instanceof ViewComponentManager.FragmentContextWrapper) {
            return getFragmentManager(((ViewComponentManager.FragmentContextWrapper) mContext).getBaseContext());
        }
        return null;
    } 

if this is the case Hope this should help someone.

happy coding.

Zeeshan Akhtar
  • 441
  • 1
  • 4
  • 9