Fragment being used by two different activties

2

I have a fragment that is inflating a recycler view, so far so good. The problem is that this fragment needs to inflate in two different navigation drawer, and at the time of casting, I can only cast one.

Is there any way to cast it, to identify which class is calling the fragment, and cast that particular class?

Below is the code that is giving error.

comunicadosList = ((NvdResp) getActivity()).getSetComunicadosList(3);
    ComunicadosAdapter adapter = new ComunicadosAdapter(getActivity(), comunicadosList);
    recyclerView.setAdapter(adapter);

In addition to the class NvdResp (which where I cast to fetch my list items to be inflated) I also have the class NvdAluno. Could I create a generic class or something like this?

    
asked by anonymous 31.08.2016 / 03:01

1 answer

0

When a Fragment needs access to Activity methods, it should force Activity to implement an interface that defines these methods.

cast can be done for the interface and not for an implementation of a particular Activity .

Begin by declaring the interface :

public interface ComunicadosListProvider {
      public ComunicadosList getSetComunicadosList(int valor);

      //Nota: substitua ComunicadosList pelo tipo da sua lista
}  

and an attribute to save an object that implements it:

ComunicadosListProvider mComunicadosListProvider;

In Fragment you should save a reference to the interface , Activity must implement this interface.

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {                           //cast feito para a interface
        mComunicadosListProvider = (ComunicadosListProvider) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
        + " deve implementar ComunicadosListProvider");
    }
}  

When you want to call the method use:

comunicadosList = mComunicadosListProvider.getSetComunicadosList(3);
ComunicadosAdapter adapter = new ComunicadosAdapter(getActivity(), comunicadosList);
recyclerView.setAdapter(adapter);
    
31.08.2016 / 13:04