lundi 5 mars 2018

Fragment root view inflated with a different classloader

I'm building an architecture on Android and I have to load Fragment from another module. How I proceed :

  1. I Inflate the view within the MainActivity
  2. Then I get it during Fragment inflation

Here the code :

In my MainActivity :

public View getModuleView(String packageName, String layoutName) throws PackageManager.NameNotFoundException {
    Context contextPackage = createPackageContext(packageName, Context.CONTEXT_INCLUDE_CODE|Context.CONTEXT_IGNORE_SECURITY); //create foreign context
    int resId = contextPackage.getResources().getIdentifier(layoutName,"layout", packageName);
    LayoutInflater myInflater = LayoutInflater.from(contextPackage);
    return myInflater.inflate(resId,null,false); //do not attach to a root view
}

In my fragment :

View rootView = ((ModuleActivity) getActivity()).getModuleView(packageName, layoutName);

The cast is for the getModuleView interface contract.

However, I can display correctly the view but when I want to get the view object I occured an error of ClassCastException because of the classloader :

java.lang.ClassCastException: android.support.v7.widget.RecyclerView cannot be cast to android.support.v7.widget.RecyclerView

I must specify, I load fragment and the MainActivity with a special DexClassloader that can loads other modules.

Do you know if I can cast across ClassLoader or I can change the ClassLoader of the rootview to make correct cast ?

Regards.





Aucun commentaire:

Enregistrer un commentaire