Dagger2子组件错误 - 必须注释方法ArrayAdapter

时间:2017-07-14 22:22:35

标签: android dagger-2 dagger

我使用https://guides.codepath.com/android/Dependency-Injection-with-Dagger-2的dagger2演示。我想在DemoDaggerSubActivity.java中使用子组件进行ArrayAdapter注入。

我的Application.java

@Override public void onCreate() {
    super.onCreate();

    mApplicationComponent = DaggerApplicationComponent.builder()
            .applicationModule(new ApplicationModule(this))
            .build();
}


public ApplicationComponent getApplicationComponent() {
    return mApplicationComponent;
}

my MyActivityModule.java

@Module
public class MyActivityModule {
private final DemoDaggerSubActivity activity;

// must be instantiated with an activity
public MyActivityModule(DemoDaggerSubActivity activity) { this.activity = activity; }

@Provides
@MyActivityScope
@Named("my_list")
public ArrayAdapter providesMyListAdapter() {
    return new ArrayAdapter<String>(activity, android.R.layout.activity_list_item);
}

}

my MyActivitySubComponent.java

@MyActivityScope
@Subcomponent(modules={ MyActivityModule.class })
public interface MyActivitySubComponent {
    @Named("my_list") ArrayAdapter myListAdapter();
}

我的ApplicationComponent.java

@Singleton
@Component( modules = {ApplicationModule.class} )
public interface ApplicationComponent {
void inject(DemoDaggerSubActivity activity);

// factory method to instantiate the subcomponent defined here (passing in the module instance)
MyActivitySubComponent newMyActivitySubcomponent(MyActivityModule activityModule);

}

我的DemoDaggerSubActivity.java

@Inject @Named("my_list")
ArrayAdapter arrayAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

((AttendanceApplication) getApplication()).getApplicationComponent().newMyActivitySubcomponent(new MyActivityModule(this)).inject(this);

}

项目重建后我遇到了错误

enter image description here

我在哪里注释方法ArrayAdapter?

1 个答案:

答案 0 :(得分:0)

必须从ApplicationComponent.java中删除inject方法并将其放入MyActivitySubComponent.java

new MyActivitySubComponent.java

@Singleton
@Component( modules = {ApplicationModule.class} )
public interface ApplicationComponent {

    // factory method to instantiate the subcomponent defined here (passing in the module instance)
    MyActivitySubComponent newMyActivitySubcomponent(MyActivityModule activityModule);

}

new ApplicationComponent.java

import util.Date;

/**
 * Class ReturnDate returns the current date.
 */
public class ReturnDate
{
    //Declare variable of type Date
    private Date date;

    /**
     * Constructor sets up the program properly
     */
    public ReturnDate()
    {
        //Create a new Date object called "date"
        date = new Date();
    }

    /**
     * Method printDate() prints the current date to the 
     * terminal window.
     */
    public void printDate()
    {
        //Print the current date to the terminal window
        System.out.println(date.toString());
    }
}