1
我很新的Dagger2刚刚开始。我想实现这样的目标,但没有成功。Dagger2如何@Provide一种具有两种不同的实现
这里是我的模块
@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);
}
}
这是我的组件
@Component(modules = UtilModule.class)
public interface UtilComponent
{
@Named("fragmentUtilActivity")
FragmentUtils fragmentUtilsActivity(Context context);
@Named("fragmentUtilFragment")
FragmentUtils fragmentUtilsFragment(Fragment fragment);
}
这是我FragmentUtil
类
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();
}
}
我想是使用fragmentUtils实例有两个不同的实现一个是针对活动和其他片段。请指导我做错了什么。
也可以有一个人请帮助我理解@Component接口无效注射(SomeClass的)的目的。
问候
任何一个......? –
你收到一个错误?请包括你面对的确切问题的描述。 –
'FragmentUtils'看起来应该是2个不同的类别:一种是与主机片段的作品,以及一个与活动工作。你有2组方法,调用错误的方法会导致NullPointerException。这是一个强烈的信号,这个代码应该被分成两个不同的类。 –