Je suis très nouveau pour Dagger2 qui démarre. Je veux réaliser quelque chose comme ça mais pas de succès.Dagger2 Comment @Fournir un type avec deux implémentations différentes
Voici mon module
@Module
public class UtilModule
{
@Provides
@Named("fragmentUtilActivity")
public FragmentUtils providesFragmentUtilForActivity(Context context)
{
return new FragmentUtils(context);
}
@Provides
@Named("fragmentUtilFragment")
FragmentUtils providesFragmentUtilForFragment(Fragment fragment)
{
return new FragmentUtils(fragment);
}
}
Et ceci est mon élément
@Component(modules = UtilModule.class)
public interface UtilComponent
{
@Named("fragmentUtilActivity")
FragmentUtils fragmentUtilsActivity(Context context);
@Named("fragmentUtilFragment")
FragmentUtils fragmentUtilsFragment(Fragment fragment);
}
Et voici ma FragmentUtil
classe
package myms.utils;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import javax.inject.Inject;
import myms.R;
public class FragmentUtils
{
private Context context;
private Fragment hostFragment;
public FragmentUtils(Context context)
{
this.context = context;
}
public FragmentUtils(Fragment hostFragment)
{
this.hostFragment = hostFragment;
}
public void addFragment(Fragment fragment, boolean addToBackStack)
{
FragmentTransaction transaction = ((Activity) context).getFragmentManager()
.beginTransaction();
transaction.add(R.id.fragment_container, fragment, null);
if(addToBackStack)
{
transaction.addToBackStack(null);
}
transaction.commit();
}
public void addNestedFragment(Fragment fragment, boolean addToBackStack)
{
FragmentTransaction transaction = hostFragment.getChildFragmentManager().beginTransaction();
transaction.add(R.id.nested_fragment_container, fragment, null);
if(addToBackStack)
{
transaction.addToBackStack(null);
}
transaction.commit();
}
public void replaceNestedFragment(Fragment fragment, boolean addToBackStack)
{
FragmentTransaction transaction = hostFragment.getChildFragmentManager().beginTransaction();
transaction.replace(R.id.nested_fragment_container, fragment, null);
if(addToBackStack)
{
transaction.addToBackStack(null);
}
transaction.commit();
}
}
Ce que je veux utiliser l'instance de fragmentUtils avec deux implémentations différentes L'une est pour l'activité et l'autre pour le fragment. S'il vous plaît me guider ce que je fais mal.
Aussi quelqu'un peut m'aider s'il vous plaît comprendre le but de l'injection de vide (SomeClass) dans l'interface @Component.
Cordialement
Quelqu'un .......? –
Vous recevez une erreur? Veuillez inclure une description du problème exact auquel vous faites face. –
'FragmentUtils' ressemble à deux classes différentes: une qui fonctionne avec un fragment d'hôte et une qui fonctionne avec une activité. Vous avez 2 ensembles de méthodes et appeler le mauvais mènera à une exception NullPointerException. C'est un signe _really_ fort que ce code devrait être divisé en 2 classes différentes. –