2017-02-12 74 views
2

獲得我有我的組件就像匕首2不注入我對象,但可以從組件

@GithubListActivityScope 
@Component(modules = { GithubListActivityModule.class,GlideActivityModule.class }) 
public interface GithubListActivityComponent { 

GithubUserListAdapter githubUserListAdapter (); 
RequestManager requestManager(); 
LinearLayoutManager linearLayoutManager(); 

} 

而且我有一個這樣的模塊:

@Module 
public class GithubListActivityModule { 
private final Activity githubListActivity; 


public GithubListActivityModule (Activity activity) { 
    this.githubListActivity = activity; 

} 

@Provides 
@GithubListActivityScope 
Activity activity () { 
    return this.githubListActivity; 
} 

@Provides 
@GithubListActivityScope 
public LinearLayoutManager linearLayoutManager(Activity activity){ 
    return new LinearLayoutManager (activity); 
} 
} 

問題: 我TREID到像這樣注入LinearLayout管理器:

@GithubListActivityScope 
@Inject 
LinearLayoutManager linearLayoutManager; 

雖然我的組件是這樣構建的:

githubListActivityComponent = DaggerGithubListActivityComponent.builder() 
      .githubListActivityModule (new GithubListActivityModule (this)) 
      .build(); 

我的線性佈局管理器沒有得到實例化。但是當我手動做

linearLayoutManager = githubListActivityComponent.linearLayoutManager(); 

它工作正常。我哪裏錯了?

回答

3

無處不在,我路過Activity,我應該傳遞準確相同類名(不是其父)每個參數所以一旦編輯和返回是"Activity""GithubListActivity"類型,然後添加

void inject(GithubListActivity activity); 

component class

然後注射內ected "GithubListActivity" 這樣的:

DaggerGithubListActivityComponent.builder() 
      .githubListActivityModule (new GithubListActivityModule (this)) 
      .build().inject (this); 

然後代碼工作對我來說..

課:
1.定義注入的方法,準確地注入電流活動

2.使用在這種情況下,相同類型的對象(不是父對象)使用「GithubListActivity」而不是僅僅是活動。

+0

這是否意味着我們將定義許多具有不同活動名稱的接口方法? – Idee

+0

如果我們不爲這個想法做其他工作,那麼是的,我們必須注入所有活動。但在互聯網上的其他一些很酷的傢伙可能也有解決方案:) – erluxman

1

Dagger 2不會自動注入字段。它也可以不注入私人領域。如果你想使用字段注入,你必須在你的@Component接口中定義一個方法,該方法將要注入的實例作爲參數(來自 - http://www.vogella.com/tutorials/Dagger/article.html#special-treatment-of-fields-in-dagger

假設你有一個你想要的片段或活動注入這些依賴關係,然後做這樣的事情 -

@Override 
public void onCreate(@Nullable Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    ((YouApplicationClass) getActivity().getApplication()).getmComponent().inject(this); 
} 

讓你的應用程序類是這樣的 -

public class YourApplicationClass extends MultiDexApplication { 

    private static final String TAG = v.class.getSimpleName(); 

    private YourComponent mComponent; 

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

     mComponent = DaggerYoutComponent.builder() 
       .yourModule(new YourModule(this)) 
       .build(); 
    } 

    public YourComponent getmComponent() { 
     return mComponent; 
    } 

    .... lots of other code 
} 

和組件類是這樣的 -

//@Singleton 
@Component(modules = {YourModule.class}) 
public interface YourComponent { 

    void inject(Fragment yourFragment); //the parameter can be any class who is invoking this method i.e. Passing the reference to itself 

    ..lots of other code 
}